- Home /
Character rotates back and forth rapidly when cursor is near the Character
I want my character to rotate towards the direction of the cursor. I've got that working fine, however, when the cursor is close to the player while moving, the player rotates rapidly (sorta looks like it's spazzing out). Here is my code:
//Get the position of the cursor
cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//Get the direction of the cursor relative to the gameObject (the ship)
direction = new Vector2(cursorPos.x - transform.position.x, cursorPos.y - transform.position.y).normalized * 20f;
Debug.Log(direction);
transform.up = direction;
I thought that by tricking the game into thinking the cursor was actually far from the player it would fix the issue, but it doesn't work either. Any suggestions?
Answer by Lentor_Gaming · Jul 06, 2019 at 03:15 PM
Answered my own question: Moving the code to LateUpdate() instead of keeping the rotation code in Update() fixes the problem. After doing some research I think it may have something to do with the camera the way it renders the rotating Object while moving. for my Main Camera, I have a camera script that follows the player as it moves in World Space and it moves using the Update() function. By using LateUpdate() for the rotation, unity makes sure it takes the Cameras already newly updated position into account and will rotate the player accordingly. This is really just an educated guess.
In addition: trying to trick the game into thinking the cursor is farther than it really is is unnecessary, simply normalize the direction using either direction.Normalized()
or direction = direction.normalized