0
\$\begingroup\$

I'm new on unity and I developed a script to move a player cube:

        var moveSpeed = 5.0f;

        var x = moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime;
        var z = moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime;

        transform.Translate(
            x,
            0f,
            z
        );

This works fine, the cube moves around the plane.

Then I wanted to make the cube rotate to face the movement, I mean, if the cube is moving to the right, face the right, etc.

the problem is when I change the transform.rotation with the direction position, there is a strange behaviour.

The movement is like WASD (the camera doesn't rotate, but I want to use Input.GetAxis("Horizontal"))

Any idea?

Thanks

\$\endgroup\$
1
\$\begingroup\$
void Update()
{
    var moveSpeed = 5.0f;

    //move relative to world space (so rotation doesn't affect movement)
    var x = moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime;
    var z = moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime;
    transform.Translate(x, 0f, z, Space.World);

    //work out angle using atan 2
    float angle = Mathf.Atan2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")) * Mathf.Rad2Deg;

    // prevent cube snapping to angle if there is no movement
    if(Input.GetAxis("Horizontal") != 0f || Input.GetAxis("Vertical") != 0f)
        transform.rotation =  Quaternion.Euler(0f, angle, 0f);
}

Atan2 is used to work out the rotation as it will take XY values and generate an angle in radians. So all we have to do is convert the radians to degrees via angle * Mathf.Rad2Deg and set it to the transform.

enter image description here

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.