Hello all, I’m working on 2D, top-down game, and am working on the player controls.
I have the following code currently controlling a player sprite:
void Update () {
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
float headingAngle = Mathf.Atan2(moveHorizontal, moveVertical);
Debug.Log("Heading angle: " + (headingAngle * Mathf.Rad2Deg).ToString() + " degrees.");
Quaternion newHeading = Quaternion.Euler(0f, 0f, headingAngle * Mathf.Rad2Deg);
if (transform.rotation != newHeading && (moveHorizontal != 0f || moveVertical != 0f))
{
Debug.Log("Turning. Rotation: " + transform.rotation + " | New Heading: " + newHeading);
transform.rotation = Quaternion.Slerp(transform.rotation, newHeading, turnSpeed * Time.deltaTime);
}
else
{
Debug.Log("Heading in the right direction, moving...");
transform.position += new Vector3(moveHorizontal * moveSpeed * Time.deltaTime, moveVertical * moveSpeed * Time.deltaTime, 0);
}
}
This code sort of works, but occasionally the player will stop moving, even though it’s rotated in the direction that the joystick is pointing. When that happens, the transform.rotation quaternion will be something like ‘(0, 0, -7, -7)’, but the newHeading quaternion will be ‘(0, 0, 7, 7)’, like they’ve flipped around. When that happens, the transform.rotation != newHeading in the if condition is always true, so the else condition is never reached.
If I keep moving the joystick to different locations, eventually the player will start moving again.
By the way, I have a sprite attached as a child to a game object, and the sprite is rotated 90 degrees in the z-axis, if that makes any difference.
Any help would be appreciated!