- Home /
Unity 2D movement and rotate sprite to the direction it is moving in
Hi, I am making a top down 2D game and i want my sprite to rotate on the Z-Axis depending on what direction it is moving. This is my code so far. I am still a beginner any help is appreciated.
public class PlayerController : MonoBehaviour {
public float speed;
private Rigidbody2D rigBod;
private Vector2 moveVelocity;
void Start ()
{
rigBod = GetComponent<Rigidbody2D>();
}
void Update()
{
if (GameObject.Find("GameManager").GetComponent<GameManager>().gameState == true)
{
PlayerControls();
}
}
void FixedUpdate()
{
if (GameObject.Find("GameManager").GetComponent<GameManager>().gameState == true)
{
PlayerMovement();
}
}
void PlayerControls()
{
Vector2 moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
moveVelocity = moveInput.normalized * speed;
}
void PlayerMovement()
{
rigBod.MovePosition(rigBod.position + moveVelocity * Time.fixedDeltaTime);
}
}
Since your question as already been answered, I just want to give you some advice. Calling GameObject.Find() and GetComponent() in any kind of Update (so FixedUpdate and LateUpdate too) is a really bad practice, because they are really slow functions that should never be called every frame. As you did for the Rigidbody, just store your Game$$anonymous$$anager reference in a variable in Start() (let's say you call it game$$anonymous$$anager) and just check if (game$$anonymous$$anager.gameState == true) in your Updates.
Answer by VeraDu · Dec 12, 2018 at 07:38 PM
Each time you move into new position, you need to calculate vector, that points from your previous position to new one (myVector = newPosition - previous Position). Then go angle = Vector2.Angle(Vector2.up, myVector ) to find z angle, corresponding to your new direction. Just set your z rotation to that angle and that's all. Hope, it helps.