Hey all ^_^
In a 2D, top-down game I’m working on, I want to have the mouse-controlled cannon follow the cursor. However, I want this to happen over time, so the cannon will rotate towards where my mouse is pointing over a certain period of time until its looking where my mouse is.
Luckily, Unity has a function for something like that – Vector3.RotateTowards! Sadly, my problem arises before the function even comes into effect, in my specific scenario.
For some bizarre reason, when I get the vector3 for where the mouse is pointing, and the vector3 of where the cannon is aimed, there’s a mishap with the numbers that just makes the RotateTowards function give really weird results.
This is more or less my code. I omitted the part where I use RotateTowards because the problem isn’t there:
//Get the mouse's position relative to the cannon, and make a Vector3 out of it. MousePosition = MyCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z - MyCamera.transform.position.z)); Vector3 TargetDir = MousePosition - new Vector3 (transform.position.x,transform.position.y,0); //I compare the values of the cannon's rotation to the vector3's rotation Debug.Log("Cannon to mouse rotation (LookRotation) - " + Quaternion.LookRotation(TargetDir) + ", Cannon rotation - " + transform.rotation);
You’d expect the rotation of the cannon and the Vector3 pointing to the mouse to be the same, if they’re the same in-game, but for some reason the values I’ve been getting are completely different – here’s an example!
Quaternions in general are pretty complex, so I’m a bit stumped as to what can be the cause of this bug. Still, I’d appreciate any help with finding why this is bugging out.
Of course, an alternative solution to rotation-to-mouse-over-time would be appreciated just as much 🙂
Thanks in advance!