D
D
Diamond2018-06-21 20:03:06
Unity
Diamond, 2018-06-21 20:03:06

How to find out if vectors are collenarian?

There is a stick that sets the direction of the character. The character turns in this direction not immediately, but after some time. Also, the character starts to shoot when turning, but the problem is that he should not shoot until he looks in the same direction that the stick shows. Is it really necessary to separately compare each coordinate through mathf.Approximately?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Basmanov, 2018-06-21
@Arios

If you are specifically interested in collinearity, then it is checked as follows:

public const float Epsilon = 0.00001f;

public static bool AreCollinear(Vector2 a, Vector2 b)
{
    return Mathf.Abs(PerpDot(a, b)) < Epsilon;
}

public static float PerpDot(Vector2 a, Vector2 b)
{
    return a.x*b.y - a.y*b.x;
}

Just keep in mind that you can't check codirectionality this way, it's better to use Vector2.Dot for this . And do not forget to normalize the vectors, otherwise you will not get what you expect.
public const float Epsilon = 0.00001f;

public static bool AreCodirected(Vector2 a, Vector2 b)
{
    return Vector2.Dot(a, b) > 1 - Epsilon;
}

If we talk about your specific case, then it's better to use Vector2.Angle or Quaternion.Angle . Just count the angle and shoot if it falls within a certain range.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question