- Home /
Face player right/left
I have a player that runs right and left. His body is always faced to the right. I want my player to face right when i make him run right and face left when i make him face left. I have a code that splits the screen into 2 buttons. Heres my code
if (Input.touchCount > 0) {
Vector3 position = Input.touches [0].position;
float movement = (position.x < (Screen.width / 2)) ? -0.05f : 0.05f;
transform.Translate (movement, 0, 0);
So how can i porgram him to face right when i press the right side of the screen and opposite? Appreciate answers.
Answer by IsaiahKelly · May 16, 2015 at 06:43 AM
Edit #1
This should work as long as the the model's forward facing direction is set to the positive Z axis (blue arrow of the transform). If not, you'll need to modify the LookRotation movement vector until it works right.
I also added Time.deltaTime to the code. Since this is needed to keep movement speed consistent. But this meant I also needed to adjust the movement float return value some. Readjust it to your liking. If you want the player to interact with physics correctly, then you should be using FixedUpdate and moving the Rigidbody instead.
void Update ()
{
if (Input.touchCount > 0)
{
Vector3 position = Input.touches [0].position;
float movement = (position.x < (Screen.width / 2)) ? -1f : 1f;
transform.rotation = Quaternion.LookRotation (new Vector3 (movement, 0, 0));
transform.Translate (-transform.right * movement * Time.deltaTime);
}
}
If you want the rotation to be smooth. Check out this answer.
Thanks for answering! The code makes my player only move one way, and not right/left. Why is that?
This was probably an issue caused by moving and rotating the object with the same vector. I rewrote the answers to hopefully fix this. Give the new code above a try.