Home > Net >  How can I get the resulting vector of rotating a vector by X degrees around another vector?
How can I get the resulting vector of rotating a vector by X degrees around another vector?

Time:07-30

For instance, I'd like to create a method that does this (But for Vector3 since I'm working in 3D):

RotateAroundPivot(Vector2 target, Vector2 pivot, Vector2 rotation)
Vector2 answer = RotateAroundPivot(new Vector2(1,0), new Vector2(0,0), 90 degrees)

In that case "answer" would be equal to (0,1).


P.S. I wrote "90 degrees" because I'm not sure how I'd write in in the form of a vector. For my use case I'd just use Quaternion.eulerAngles for the rotation vector.

CodePudding user response:

Here's a function that should do the trick :

Rotate around Vector3 :

public static Vector3 RotateAround(Vector3 src, Vector3 pivot, Vector3 angle)
{
    var direction = src - pivot;

    var rotated = Quaternion.Euler(angle) * direction;

    return rotated   pivot;
}

If you want to rotate your object 90° on the Y axis you can call the function like that :

var pivotTransform = pivotGameObject.transform;
transform.position = RotateAround(transform.position, pivotTransform.position, new Vector3(x:0, y:90, z:0));
  • Related