Search Unity

Rotate a point around a second point, using a Quaternion

Discussion in 'Scripting' started by NotQuiteSmith, Nov 17, 2017.

  1. NotQuiteSmith

    NotQuiteSmith

    Joined:
    Oct 27, 2013
    Posts:
    92
    Could someone please help with the code required to rotate point P1 around point P2 by angle (x1,y1,z1)? Points are stored as Vector3, angle comes from transform.rotation (Quaternion). I saw transform.RotateAround but this is happening in a non-gameobject class so I don't have a "transform" as such (unless someone can tell me how I get one).

    e.g. I have a Vector3 point e.g. (3,0,0) and I want to rotate this around another point e.g. (1,0,0) by 90 degrees around Y. This should give me (1,0,2) (I think!).

    Thanks!
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,532
    Get a vector from P2 to P1 to get the relative change in direction
    multiply that by the quat to rotate it
    add P2 back to the result to bring it back to being around P2

    Code (csharp):
    1.  
    2. Vector3 P1, P2; //your points
    3. Quaternion rot; //the rotation
    4.  
    5. var v = P1 - P2; //the relative vector from P2 to P1.
    6. v = rot * v; //rotatate
    7. v = P2 + v; //bring back to world space
    8.