Search code examples
mathvector3dunreal-engine5unreal-blueprint

How to get a 3D vector in the same direction as another vector limited by an angle?


If I have two 3D vectors as shown by the blue and red vector in the image below, where the red vector is at an angle of more than 20 degrees from the blue vector, how could I calculate a new vector (green in the example) that is exactly 20 degrees away from the blue, in the same direction as the red one? It doesn't need to have the same length as the red one, ideally it would be a unit (normalized direction) vector. How would I do this if the arbitrary angle limit would be a variable named x?

Example image

For context: I am making a video game where I get the location of where the player is aiming and draw a Linetrace from the weapon muzzle to the player aim location. However if this Linetrace is more than x degrees off from the actual direction the weapon is pointing I want the weapon to fire x degrees in the direction of the players aim so that it cant just shoot sidewards.

If you are able to give the answer as unreal engine 5.x blueprints that would be amazing but not necessary. I can just convert the pure math to blueprints myself.


Solution

  • As fas as I understand the problem, in the same direction here denotes that vectors Blue, Read and Green are coplanar.

    So you can use spherical linear interpolation (SLERP). Normalize vectors B and R, get angle between them

    Ω = acos(B.dot.R)
    

    and build G (here θ=20 degrees)

    G = B * sin(Ω - θ)/sin(Ω)   +   R * sin(θ)/sin(Ω)
    

    Alternative is to make rotation axis perpendicular to B and R and rotate B around it (looks more complex, but perhaps your library has appropriate functions)

    R = B x R (vector product)
    M = matrix to rotate B around R by 20 degrees
    G = M * B