- Home /
Making player face the direction it moves (using angles).
I'm making a top-down 2D game. But I can't make my player object to rotate to the direction it's moving.
void Update() {
float HorizontalMove = Input.GetAxis ("Horizontal");
float VerticalMove = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (HorizontalMove, 0.0f, VerticalMove);
float newAngle = Vector3.Angle (transform.forward, movement);
transform.rotation = Quaternion.AngleAxis (newAngle, Vector3.forward);
}
This code makes my object face the direction I want, however, this works only for the left direction. When I move right, it still rotates to the left. Also, I want the script to remember the last angle and add it up to the next one, so that the object always faces where it goes.
Sorry for my bad English. Maybe it'll become better someday.
Comment
Best Answer
Answer by robertbu · Jan 10, 2014 at 09:38 PM
You are close. Try this:
void Update() {
float HorizontalMove = Input.GetAxis ("Horizontal");
float VerticalMove = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (HorizontalMove, 0.0f, VerticalMove);
float newAngle = Mathf.Atan2(movement.y, movement.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis (newAngle, Vector3.forward);
}
Vector3.Angle() returns an unsigned angle. It doesn't take much to calculate a signed angle, but Atan2() is a good fit for this application.