Players moves with simple script, but dont look where he moves

Hello all.

Sorry for my stupid question; my little script allows player to move in X and Z axis.

But he don’t look where he moves…


public class PlayerMovement : MonoBehaviour
{
Animator anim;
Rigidbody playerRigidbody;
Vector3 movement;

void Awake()
{
          anim = GetComponent<Animator>();
    playerRigidbody = GetComponent<Rigidbody>();

}

void Animating(float h, float v)
{
   bool walking = h != 0f || v != 0f;

   anim.SetBool("IsWalking", walking);
}
void FixedUpdate()
{

	var x = Input.GetAxis("Horizontal") * Time.deltaTime * 15.0f;
	var z = Input.GetAxis("Vertical") * Time.deltaTime * 15.0f;
    
	transform.Translate(x, 0, z);

	Animating(x,z);
}

}

You only tell the transform to translate in the direction you move. You also need to explicitly tell it to turn towards that direction. You can do this with the LookAt-method which will turn a transform to face a specific position:

transform.LookAt(transform.position + new Vector3(x, 0, z));

EDIT:

Now that your character is turning you also need to take into account that the method signature for Translate() is:

public void Translate(Vector3 translation, Space relativeTo = Space.Self);

This means that if you do not att the second parameter it will assume you want to move in the transform’s local space, i.e. positive x axis is the right hand side of your character. If this is not the intended behaviour then you should write this instead:

transform.Translate(new Vector3(x, 0, z), Space.World);

Personally, I prefer to always specify which space to use as I tend to forget which one is the default :slight_smile:

Thank you so much for your quick reply !

I’ve tried this script, and now thr player moves only in 2 directions :

With Up or Down button : he moves diagonally to down of the screen.
with left or right : he moves diagonally to up of the screen.

(if you imagine what i’m sayin’)

Thank you and sorry for this question.