Search Unity

Question Use a normalized vector as the rotation of a transform

Discussion in 'Scripting' started by Filter_Feeder, Nov 26, 2022.

  1. Filter_Feeder

    Filter_Feeder

    Joined:
    Oct 19, 2017
    Posts:
    45
    So let's say we have a box floating and rotating around freely in space.

    I have a Vector3, let's say that it has the value of (-1,0,0). We can arbitrarily interpret this as "left".

    I now want to spawn a pole or some elongated object that points left from the box, just based on this vector. Obviously, the pole should have some rotation around the vector, or around the x-axis in this case, but let's just say that this rotation should be the same as the box.

    I know that I can get the direction of this vector, based on the box's current rotation by saying:

    Code (CSharp):
    1. Vector3 rotatedVector = box.transform.rotation * myVector;
    However, how can I apply this rotation such that the rotation of the "pole" makes it "point" in the direction the vector points?
     
  2. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,998
    transform.rotation = Quaternion.LookRotation(rotatedVector);
    converts a direction vector into a rotation.

    It's not as common as
    transform.LookAt(target)
    , but pretty much does real work (LookAt first finds the difference between positions as a vector:
    vec=target-transform.position
    , then uses LookRotation(vec) to get the rotation facing that way, then auto-assigns it to our rotation).