Clamp an unit vector in a cone.

NeoDNeoD Posts: 179Member
in 2D

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


  • cyberealitycybereality Posts: 927Moderator
    Accepted Answer

    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.

    var 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.

  • cyberealitycybereality Posts: 927Moderator

    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.

  • CalinouCalinou Posts: 417Admin Godot Developer
    edited June 29

    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.

Leave a Comment

BoldItalicStrikethroughOrdered listUnordered list
Align leftAlign centerAlign rightToggle HTML viewToggle full pageToggle lights
Drop image/file