圆形敌人仇恨检测条件?(纯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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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