简体   繁体   中英

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

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM