- Home /
A small problem with rotating object at mouse position
Hello. I want to rotate and schoot a bullet on mouse position. Thats my script so far:
if (Input.GetButtonDown("Fire1"))
{
clickPos = -Vector3.one;
Vector3 punktA = new Vector3(1, 2, 0);
Vector3 punktB = new Vector3(2, 1, 0);
Vector3 punktC = new Vector3(3, 3, 0);
Plane plane = new Plane(punktA, punktB, punktC);
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
float DistanceToPlane;
if (plane.Raycast(ray, out DistanceToPlane))
{
clickPos = ray.GetPoint(DistanceToPlane);
}
Vector3 finalClickPos = new Vector3(clickPos.x, clickPos.y, 1);
Instantiate(bullet, transform.position, Quaternion.LookRotation (finalClickPos));
}
The problem is that this script rotates bullet on opposite direction (when i click upper left it rotates towards upper right). How can i fix it? thanks
I would recommend reading through Quaternion docs. This blog post might be useful too: rotations in unity
Why do you use that plane for raycast? Also, you can make a raycasthit to store the position it hits directly ins$$anonymous$$d of using that ray.getPoint
Becouse other solution doesnt work (for instance camera.main.screentoworldpoint). When i implement code like this:
clickPos = -Vector3.one;
clickPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
clickPos.z = 0;
Instantiate(bullet, transform.position, Quaternion.LookRotation(clickPos));
I get error "object reference not set to an instance of object" and idk what i should do with it.
It might be worth trying to fix this rather than using a plane, which you need to always set according to how camera is facing in order to work well.
Per your plane coordinates, it looks as if you wanted to use -/Vector3.forward as a second parameter to Quaternion.LookRotation(), ins$$anonymous$$d of the default Vector3.up
Sorry, but i dont understand. I cant replace clickpos.y with -Vector3.forward , changing PunktB does not work
Does Instantiate(bullet, transform.position, Quaternion.LookRotation (finalClickPos, Vector3.forward)); solve the problem? (or -Vector3.forward). A wild guess anyways :)
Answer by thunderbuns · Nov 10, 2018 at 01:47 AM
Try instantiating the object with no rotation. Assign the object to a new variable name it whatever you want. Then call whatEverYouWant.transform.LookAt(finalClickPos);
.
Your answer
![](https://koobas.hobune.stream/wayback/20220612181757im_/https://answers.unity.com/themes/thub/images/avi.jpg)