圆形敌人仇恨检测条件?(纯JS的2D游戏)

我正在尝试为敌人仇恨检测编写一个圆形的检测区域。目前,如果玩家的x和y位置与敌人x和y位置及其仇恨范围(aggroDist)相撞,敌人就会被触发。

这是当前的代码:

if (player.x > enemies[e].x -enemies[e].aggroDist &&     player.x < enemies[e].x +enemies[e].aggroDist &&     player.y > enemies[e].y -enemies[e].aggroDist &&     player.y < enemies[e].y +enemies[e].aggroDist) {        enemies[e].isAggro = true;        console.log(enemies[e].isAggro);    }

这种方法的问题在于检测区域是方形的,这意味着敌人在对角线边缘可以检测到更远距离的玩家。

enter image description here

我尝试使用类似enemies[e].x + (enemies[e].aggroDist * Math.PI)的方法来创建一个圆形的检测区域,但我不知道如何实现(可能是因为这种方法也是错误的)。

有什么办法可以使检测区域中心与边界之间的所有距离严格相等吗?


回答:

这是一个使用距离公式的粗略实现:

//Load HTML elementsvar c = document.getElementById("c");var ctx = c.getContext("2d");//Distance function function distance(x1, y1, x2, y2) {    return Math.sqrt((x2 -= x1) * x2 + (y2 -= y1) * y2);}//Entity is the player, radius is the aggro distancevar entity = { x: 200, y: 200, radius: 50 };//Radius is the aggro distance of the other entitiesvar radius = 2;//Draw playerctx.beginPath();ctx.arc(entity.x, entity.y, entity.radius, 0, 2 * Math.PI);ctx.stroke();ctx.closePath();//Loop through "X" and "Y" combinations and draw "enemies"for (var x = 0; x < 400; x += 10) {    for (var y = 0; y < 400; y += 10) {        //Get distance between "enemy" and "player"        var d = distance(x, y, entity.x, entity.y);        //If the distance is less than the combined aggro distances, turn red, else turn green        ctx.strokeStyle = (d < entity.radius + radius ? "red" : "green");        //Draw enemy        ctx.beginPath();        ctx.arc(x, y, radius, 0, 2 * Math.PI);        ctx.stroke();        ctx.closePath();    }}
<canvas id="c" height="400" width="400"></canvas>

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注