与玩家相比,我在检查游戏对象是否在特定半径内时遇到困难。
我的游戏对象包含一个半径,我想使用该半径进行检查,但是我失败了。
这是我到目前为止所拥有的:
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;
}
我正在尝试使用XNA框架在C#中执行此操作。
PosX和PosY均来自当前gameObject的位置。而currentTarget目前仅是玩家的位置。
您正在混合x和y。
检查currentTarget.X在左右PosX极限之间。没有左和上。这样想让我的头很痛!
我将用伪代码对此加以充实。
if(
(target.x > my.x -radius && target.x < my.x +radius) &&
(target.y > my.y -radius && target.y < my.y +radius)
){ ... }
请注意,这会检查边界框,严格来说不是半径。但这在许多情况下就足够了。
所以最后应该是:
if (currentTarget.X > PosX - BRadius && currentTarget.X < PosX + BRadius) &&
(currentTarget.Y > PosY - BRadius && currentTarget.Y < PosY + BRadius)
{ return true; }
我过去曾使用Vector2.Distance()来确定游戏对象是否靠近玩家对象。我们可以使用它返回一个浮点数,然后我们可以检查游戏对象是否在一定半径内。
[如果您专门查看游戏对象是玩家的右上角,左下角等,那么不幸的是,这没有太大帮助。
在有问题的情况下:
public bool IsInRange(Vector2 currentTarget) {
Vector2 yourPos = new Vector2(PosX, PosY);
return BRadius >= Vector2.Distance(yourPos, currentTarget);
}
根据circle-circle collision(这是关于球体命中检测的冗长讨论)您只需要检查x到中心的距离即可。如果距离大于半径,则可以。考虑到两个对象都有球形的命中框,只需解决(x2-x1)^2 + (y1-y2)^2 <= (r1+r2)^2
。