Jeron
Jeron

Reputation: 36

Check If the point Inside Arc

I am trying to make this works, but have no success. Here the simple case with 2 Vector2 (origin & Target) and angles for ship & turret rotation plus arc size.

    var ship1 = new Vector2(0, 0); //start
    var ship2 = new Vector2(0, 200); //Up

    float shipAngle = 0f; // Up
    float turretAngle = 0f; //Front

    float turretRadius = 90f;

    bool result = CheckIfInsideFireArc(ship1, ship2, shipAngle, turretAngle, turretRadius);

The expected result here is true, but it's false.

Function for CheckIfInsideFireArc:

public static bool CheckIfInsideFireArc(Vector2 own, Vector2 target, float shipDir, float turretDir, float fireArc)
{

    Vector2 pos = target;
    float halfArc = fireArc / 2f;
    Vector2 toTarget = pos - own;
    float radians = (float)Math.Atan2(toTarget.x, toTarget.y);
    float angleToMouse = 180f - radians.ToDegrees();
    float facing = turretDir.ToDegrees() + shipDir.ToDegrees();
    if (facing > 360f)
    {
        facing = facing - 360f;
    }
    float difference = 0f;
    difference = Math.Abs(angleToMouse - facing);
    if (difference > halfArc)
    {
        if (angleToMouse > 180f)
        {
            angleToMouse = 1f * (360f - angleToMouse);
        }
        if (facing > 180f)
        {
            facing = 1f * (360f - facing);
        }
        difference = Math.Abs(angleToMouse - facing);
    }

    if (difference < halfArc)
    {
        return true;
    }
    return false;
}

I am trying to achieve something like: enter image description here But looks like doing something wrong... So, how i can do this?

Upvotes: 0

Views: 118

Answers (1)

MBo
MBo

Reputation: 80187

Get middle angle and half-angle (note that start and end should be normalized: end>start)

if end < start then
   end = end + 2 * Pi

half = (end - start) / 2
mid  = (end + start) / 2
coshalf = Cos(half)

Now compare that difference of angle and range middle is less then half-angle.

Cosine solves potential troubles with periodicity, negative values etc.

  if Cos(angle - mid) >= coshalf then
        angle lies in range

Upvotes: 1

Related Questions