如何判断一个物体是否在另一个物体的距离内?

How to tell if an object is within a distance of another?

我有一个角色对象和一个粘液对象。角色可以移动,史莱姆使用下面的代码移动到玩家身边。

(player_obj是字符)

phy_position_x += sign(player_obj.x - x) * 0.2;
phy_position_y += sign(player_obj.y - y) * 0.2;

我怎样才能让粘液在任何距离都不会移动到角色身上?如何设置史莱姆开始移动到角色的半径?

是否有一个 if 语句如下:

if slime_obj.x < 20 to player.obj.x and slime_obj.y < 20 to player_obj.y {}

要做到这一点相当简单,您只需使用 the distance formula 计算距离即可。您可以在 GML 中使用 point_distance 函数。它看起来像这样:

if (point_distance(x, y, obj_player.x, obj_player.y) < r) {
    //Move towards the player
}

其中 'r' 是您希望敌人跟随玩家进入的圆圈的半径。

更多信息,您可以在这里查看:http://docs.yoyogames.com/source/dadiospice/002_reference/maths/vector%20functions/point_distance.html

不过,这计算起来相当昂贵(对于 CPU),因为它使用平方根函数。尽管对此的补救措施相当简单。您将创建以下脚本(我将其命名为 point_distance_squared,但您可以随意命名):

///point_distance_squared(x1, y1, x2, y2)
var x1 = argument[0];
var y1 = argument[1];
var x2 = argument[2];
var y2 = argument[3];
return (pow(pow(x2, 2) - pow(x1, 2), 2) + pow(pow(y2, 2) - pow(y1, 2), 2));

那么代码几乎是一样的,除了你需要平方半径,它看起来像这样:

if (point_distance_squared(x, y, obj_player.x, obj_player.y) < (r * r)) {
    //Mode towards the player
}