Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Confusion about moving in local space and inverting transform direction

Discussion in 'Scripting' started by GemShards, Oct 20, 2019.

  1. GemShards

    GemShards

    Joined:
    May 8, 2018
    Posts:
    10
    Hello,

    I am getting rather confused about how moving in local space of an objects axis works.

    I have a basic capsule in a scene, no parent - I have the following code:

    Code (CSharp):
    1.     void Update()
    2.     {
    3.         moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
    4.         moveRotation = new Vector3(0f, Input.GetAxis("MouseX"), 0f);
    5.  
    6.         this.transform.Rotate(moveRotation * turnSpeed, Space.Self);
    7.  
    8.         Vector3 invertedMoveDirection = this.transform.TransformDirection(moveDirection);
    9.         characterController.Move((invertedMoveDirection * moveSpeed) * Time.deltaTime);
    10.     }
    I get that the moveDirection code applies basic values in the worlds global X and Z axis, So I need to apply that to the capsules local X and Z axis as it rotates.

    This code works, but I can't work out why I need to use TransformDirection, which "Transforms direction from local to world space"

    So, my understanding is:

    Move direction is a positive or negative value of 1 on X and Z axis in world space.

    I then take that world space vector, and convert it to world space based on the capsules transform direction?

    This then lets me move relative to the capsules local X and Z axis and not the global X and Z axis.

    I mean, this all works, I just can't understand why it works, which is the biggest problem for me at the moment.
     
  2. Olmi

    Olmi

    Joined:
    Nov 29, 2012
    Posts:
    1,553
    Hi @GemShards

    You essentially have your movement in local space, don't you? You get your character's local sideways movement to the x component of the Vector3, and local forward/backward to the z component.

    Then you rotate your object and after that you apply the movement. TransformDirection transforms the vector direction from local space to the world space.

    For example (without that TransformDirection) if you would have turned your character 30 degrees to the left, your movement vector (if it was 0,0,1) wouldn't move it to that 30 degrees left "forward" direction, which would be the local forward? It would just go that very same z-axis direction, no matter how you turn.
     
    Last edited: Oct 20, 2019