Home > Blockchain >  how do I rotate a direction Vector3 upwards by an angle in unity
how do I rotate a direction Vector3 upwards by an angle in unity

Time:04-02

this is my direction vector new Vector3(target.transform.position.x - projectile.position.x, 0, target.transform.position.z - projectile.position.z).normalized

I tried multiplying it by Quaternion.AngleAxis(45, Vector3.up) but that simply doesn't work All other orientations like Vector3.left, right, etc. don't help either

The only thing I could observe is the way that the angle changes when I move the target or projectile

CodePudding user response:

You were close. Use cross product to get the axis you need, use that in AngleAxis, then finally apply that rotation to your starting direction:

Vector3 RotateTowardsUp(Vector3 start, float angle)
{
    // if you know start will always be normalized, can skip this step
    start.Normalize();

    Vector3 axis = Vector3.Cross(start, Vector3.up);

    // handle case where start is colinear with up
    if (axis == Vector3.zero) axis = Vector3.right;

    return Quaternion.AngleAxis(angle, axis) * start;
}
  • Related