- Home /
Unity 2d Top-Down Mouse Aiming Stutters When Moving
I'm creating a top-down that uses the mouse position to determine character and flashlight rotation. The problem is that it the aiming shakes/stutters. This is especially noticeable when the mouse is closer to the character; completely spazzing out when the mouse is directly on top of the character. I've spent some time looking for a solution and playing around on my own, but I haven't been able to find anything.
void FixedUpdate
{
float fAngle;
Vector3 pos = Input.mousePosition;
pos.z = player.transform.position.z - Camera.main.transform.position.z;
pos = Camera.main.ScreenToWorldPoint(pos);
pos = pos - player.transform.position;
fAngle = (Mathf.Atan2 (pos.y, pos.x) * Mathf.Rad2Deg);
this.gameObject.transform.rotation = Quaternion.Euler(fAngle - 180, 270f, 0f);
}
This is the code that I'm using to rotate the flashlight. The character rotation code is identical. The issue is extremely noticeable with the flashlight.
It appears that Input.mousePosition is not being updated frequently enough.
Any ideas would be greatly appreciated.
Answer by DanRigg11 · Aug 27, 2015 at 09:36 AM
hi i used this tutorial hope it helps https://www.youtube.com/watch?v=F5a4Xo6ijLE∈dex=5&list=PLBLzRnRotAkpX851-d_hEpV7dOVkCUMPF
Answer by jimbobulus2 · Aug 28, 2015 at 06:12 PM
Hi @RogerTheJolly Try using Update() instead of FixedUpdate(). FixedUpdate() runs at a fixed time step. Or, try adding a Lerp to the Quaternion to smooth out the animation:
this.gameObject.transform.rotation = Quaternion.Lerp(this.gameObject.transform.rotation, Quaternion.Euler(fAngle - 180, 270f, 0f), Time.deltaTime );
http://docs.unity3d.com/ScriptReference/Quaternion.Lerp.html
If you want to adjust the smooth speed, multiply the Time.deltaTime by something.
I also made a tutorial on rotating 2D using the z-axis with an example project that might be useful