Clamp an unit vector in a cone.
Hello I'm looking for a way to limit a unit vector between two vectors.
Imagine an I.A controlled entity that throw objects to the player. At first the entity A simply targets the player at B.
If the resulted vector AB is between the vectors AR and AL, all is fine, there is nothing to do. If the object direction is outside these vectors the final projectile vector will be the nearest of AR and AL.
I have some complicated ideas but I'm sure there is some math functions for that. Sorry if it's obvious for you.
Best Answer

cybereality Posts: 927
Vector2 has a function "angle" which gives you the radian angle of a vector. You can use this to get the angle of all 3 vectors and them use the clamp function to limit it to stay in the middle.
https://docs.godotengine.org/en/stable/classes/class_vector2.html#classvector2methodanglevar ar = (r  a).angle() var al = (l  a).angle() var ab = (b  a).angle() ab = clamp(ab, ar, al)
You may need to also figure out which angle is smaller and bigger for clamp to work, but that is not hard.
Answers
Vector2 has a function "angle" which gives you the radian angle of a vector. You can use this to get the angle of all 3 vectors and them use the clamp function to limit it to stay in the middle.
https://docs.godotengine.org/en/stable/classes/class_vector2.html#classvector2methodangle
You may need to also figure out which angle is smaller and bigger for clamp to work, but that is not hard.
I forgot to mention, there may be issues when the angle is around 0 degrees, so that could may not work exactly as shown, but maybe that will give you some ideas to work with.
You could probably use a mix of a
clamp()
ed vector length (to limit the distance) and a dot product (to limit the angle). See Vector math in the documentation for more information.