Search code examples
c#xnarangecollision-detectiongeometry

How to check if a gameObject is within a specific radius?


I'm having difficulties with checking if a gameobject is within a specific radius compared to the player.

My gameobject contains a radius and i want to use that for the checking yet i fail.

This is what i had so far:

public bool IsInRange(Vector2 currentTarget)
{

    if ((currentTarget.X >= PosX - BRadius && currentTarget.Y >= PosY - BRadius) || // left up
        (currentTarget.X >= PosX - BRadius && currentTarget.Y <= PosY + BRadius) || // left down
        (currentTarget.X >= PosX + BRadius && currentTarget.Y >= PosY + BRadius) || //right up
        (currentTarget.X >= PosX + BRadius && currentTarget.Y <= PosY - BRadius)) //right down
    {
        return true;
    }
    return false;
}

I'm trying to do this within C# using the XNA framework.

PosX and PosY are from the current gameObject his position. And the currentTarget is for now only the player's position.


Solution

  • You are mixing your x's and y's.

    Check the currentTarget.X is between the PosX extremes left & right. Not left and top. It makes my head hurt thinking that way!

    I'll flesh this out a little in pseudo-code.

    if(
      (target.x > my.x -radius && target.x < my.x +radius) &&
      (target.y > my.y -radius && target.y < my.y +radius)
    ){ ... }
    

    Note this checks for a bounding box, not strictly speaking a radius. But that is sufficient in many cases.

    So in the end it should be:

    if (currentTarget.X > PosX - BRadius && currentTarget.X < PosX + BRadius) &&
       (currentTarget.Y > PosY - BRadius && currentTarget.Y < PosY + BRadius)
            { return true; }