Search Unity

Question How to transform from worldspace to localspace and back with new math library?

Discussion in 'Entity Component System' started by Cell-i-Zenit, Oct 25, 2020.

  1. Cell-i-Zenit

    Cell-i-Zenit

    Joined:
    Mar 11, 2016
    Posts:
    290
    Hi,

    I need to convert some old code, but i cannot find the right methods in the new math library :D

    Can you guys help me?

    Code (CSharp):
    1.  
    2. var localMovement= transform.InverseTransformDirection(_rigidbody.velocity);
    3. //[...] some transformation of localMovement
    4. _rigidbody.velocity = transform.TransformDirection(localMovement);
    5.  
     
  2. NotaNaN

    NotaNaN

    Joined:
    Dec 14, 2018
    Posts:
    325
    :D

    This should do it:
    Code (CSharp):
    1.  
    2. var localMovement= math.rotate(math.inverse(transform.rotation), _rigidbody.velocity);
    3. //[...] some transformation of localMovement
    4. _rigidbody.velocity = math.rotate(transform.rotation, localMovement);
    5.  
    The important thing here is that Unity.Mathematics.math works with Unity.Mathematics.quaternion, which you will be using a lot. Unity.Mathematics.quaternion has some quirks, though. Such as .Euler requiring Radians instead of Degrees.
     
    Last edited: Oct 25, 2020
    Onigiri and Cell-i-Zenit like this.
  3. Cell-i-Zenit

    Cell-i-Zenit

    Joined:
    Mar 11, 2016
    Posts:
    290
    You are a lifesaver, this works flawlessly :D:)
     
    NotaNaN likes this.
  4. Opeth001

    Opeth001

    Joined:
    Jan 28, 2017
    Posts:
    1,113
    NotaNaN likes this.