- Home /
Sprite will not roate when arrow keys are pressed
void Update()
{
if(Input.GetKey("right"))
{
rotatePlayer(true);
gameObject.transform.position = new Vector2(transform.position.x + 0.1f, transform.position.y);
}
if(Input.GetKey("left"))
{
rotatePlayer(false);
gameObject.transform.position = new Vector2(transform.position.x - 0.1f, transform.position.y);
}
}
void rotatePlayer(bool isMovingRight)
{
if (isMovingRight)
{
if (gameObject.transform.rotation.eulerAngles.y == 180)
{
gameObject.transform.Rotate(0, 0, 0);
}
}
if(!isMovingRight)
{
if (gameObject.transform.rotation.eulerAngles.y == 0)
{
gameObject.transform.Rotate(0, 180, 0);
}
}
}
The sprite rotates to face left the first time I press the left arrow but after that, the sprite stays facing no matter which arrow key I press. Why won't it rotate to face the direction of the arrow key that is pressed?
Answer by cgklutts · Dec 22, 2019 at 12:58 PM
I have a feeling that when I answer this question its going to give you unwanted results.. What exactly are you trying to accomplish? Is this a top down game where you push left and right to change the player into 1 of 4 directions? Is this a 2D side game where the player moves left and right?
Answer by Priyanka-Rajwanshi · Dec 23, 2019 at 02:19 PM
@YellowSock There are few issues in the code:
Firstly, gameObject.transform.rotation.eulerAngles.y is a float value and it you try and debug its position, it would never be equal to an exact zero or exact 180.
Secondly, transform.Rotate(0, 180, 0) will rotate the object by 180 in y-axis everytime. If you want that when right is pressed, the rotation should be (0,0,0) and (0,180,0) for left, use
transform.eulerAngles = new Vector3(0,0,0);
and
transform.eulerAngles = new Vector3(0,180,0);