Search Unity

Question Rotate Vector3 Based on the Rotation of a Transform

Discussion in 'Editor & General Support' started by Filter_Feeder, Nov 21, 2022.

  1. Filter_Feeder

    Filter_Feeder

    Joined:
    Oct 19, 2017
    Posts:
    45
    This was sort of hard to google down because googling only gives very basic guides on how to rotate a transform. In my particular case, I have a transform that has some arbitrary rotation, and then I have a Vector3 which has some direction, let's say it's pointing up.

    I now want to be able to rotate this vector based on the rotation on the transform, so that if the transform is upside down, the vector is now point down instead of up.

    Cheers!
     
  2. Filter_Feeder

    Filter_Feeder

    Joined:
    Oct 19, 2017
    Posts:
    45
    Never Mind, I found it when looking through the Quaternion Methods.

    Quaternion.FromToRotation(myVector, transform.rotation.eulerAngles).eulerAngles;
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,748
    Hm, not sure about that one. Anytime you reach into .eulerAngles you are setting yourself up for lots of future confusion and weird edge case bugs. Here's why:

    All about Euler angles and rotations, by StarManta:

    https://starmanta.gitbooks.io/unitytipsredux/content/second-question.html

    Based on your description:

    you just multiply the Vector3 by the Quaternion:

    Code (csharp):
    1. Vector3 myRotatedVector = transform.rotation * myOriginalVector;
    That's it.
     
  4. Filter_Feeder

    Filter_Feeder

    Joined:
    Oct 19, 2017
    Posts:
    45
    You're right. I though it was working but it was just on that instance that made it look like it was working. I stumbled across this solution on some other forum, but thanks anyway!