How transform.Direction with math works?

Hello.

First. I’m sorry if my english it’s not the best.

Second, I’m curious, and can’t stop thinking how that code work using maths?

 [SerializeField] CameraController cam = null;

    private float moveX, moveZ, speed = 0f;

    Vector3 direction = Vector3.zero;

    private void Awake()
    {
        speed = 10f;
    }

    void Update()
    {
        moveX = Input.GetAxisRaw("Horizontal");
        moveZ = Input.GetAxisRaw("Vertical");

        direction = speed * Time.deltaTime * new Vector3(moveX, 0f, moveZ);

        direction = transform.TransformDirection(direction);
    }   

    private void FixedUpdate()
    {
        this.transform.rotation = Quaternion.Euler(0f, cam.getRotY, 0f);
        this.transform.position += direction;
    }

I was looking for ways to make my player move where my cam it’s looking when I pressed “W” and transform.Direction was my solution but I want to know, how I can create that “transform.Direction” with math?. Thank you.

Hello.

You need to understand the difference between local/object reference (Local space) and global/world reference (world Space).

Local reference vectors, use the transform of the object, world reference use the global reference.

Some functions use local reference, other uses world references. For example:

object.transform.position += new vector3 (1,0,0);

This will move 1 in X world axis, always. But…:

object.transform.translate(new Vecotor3(1,0,0));

This will move the object 1 forward, in the direction the object is looking at in that moment.

Also, you can chage one vector from local reference to wolrd reference, and viceversa with:



Also works for rotations and sclae of objects.

You should go look for a tutorial about this topic. It can be little confusing at the begining, but its really simple and important to understand.

Mostimportant thing is to know when you want to apply some movement or rotation or something if need a world reference or a local reference.

Bye!!