Baklap4
Baklap4

Reputation: 4202

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.

Upvotes: 1

Views: 3067

Answers (3)

I've used Vector2.Distance() in the past to find out if a game object is near the player object. We can use this to return a float, and from this we can check if the game object is within a certain radius.

If you are specifically looking to see if a game object is top-right, bottom-left, etc of the player then this will not help much unfortunately.

In the question case:

public bool IsInRange(Vector2 currentTarget) {
    Vector2 yourPos = new Vector2(PosX, PosY);
    return BRadius >= Vector2.Distance(yourPos, currentTarget);
}

Upvotes: 2

srm
srm

Reputation: 127

According to circle-circle collision (which is a lengthy discussion on hitdetection on spheres) you should just check the distance of x from the center of your cirlce. If the distance is greater than the radius, you are fine. Just solve (x2-x1)^2 + (y1-y2)^2 <= (r1+r2)^2, given that both objects have spherical hitboxes.

Upvotes: 0

Matt Stevens
Matt Stevens

Reputation: 1114

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; }

Upvotes: 1

Related Questions