Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unity transform.Translate changed object directions not as expected

I’m trying to move an object by doing the following :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{

    public float speed;
    // Update is called once per frame
    void Update()
    {
        float horznotalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        Vector3 movment = new Vector3(horznotalInput,0,verticalInput);
        transform.Translate(movment * Time.deltaTime *speed);
    }
}

But something weird happens to the object’s movement.

when pressing on "a" key the object goes up

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"d" goes down.

"w" goes right

and "s" goes left.

When I’m changing it to the following:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{

    public float speed;
    // Update is called once per frame
    void Update()
    {
        float horznotalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        float newHorizontalPosition = transform.position.x + horznotalInput * Time.deltaTime;
        float newVerticalPosition = transform.position.z + verticalInput * Time.deltaTime;

        transform.position = new Vector3(newHorizontalPosition,transform.position.y,newVerticalPosition);


    }
}

It’s working as expected.

Now, I’m following a tutorial and I copied the same as he does.
But It’s not working for me.

Any help please?

Thanks!

>Solution :

Translate by default uses local space!

It sounds like your object (or some parent in the hierarchy) is rotated by 90°.

If you wanted global axis you should rather use

transform.Translate(movment * Time.deltaTime * speed, Space.World);

or to simplify your second snippet you can also do

transform.position += movment * Time.deltaTime * speed;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading