English 中文(简体)
检查敌方周围的玩家圆环区域
原标题:Checking circular area around enemy for player

我正在玩 HTML 5 游戏, 并且有我所想的数学问题。 玩家和敌人对象有一个 pos.x 和 pos. y 值, 显示它们在屏幕上的位置 。 我对一些敌人实施了近距离检查代码, 并不完全满意 。 目前敌人正在检查玩家是否在距离它一定的距离内, 在 x 和 y 轴上是200 或 - 200 。 这意味着这个实体正在扫描一个400x400 平方。

我想把这个圆做成一个半径为200的圆圈。我的代码是现在的。

if ((player.pos.x - enemy.pos.x > 200 && player.pos.x - enemy.pos.x < 200) 
  && (player.pos.y - enemy.pos.y > 200 && player.pos.y - enemy.pos.y < 200)) {
    //Do something...
}

如果您想要检查的话, 请在这里玩我的游戏 。 接近敌人在第二层, 目前是最后一层 : )

http://project.dnsalias.com/" rel="no follow" >http://project.dnsalias.com/

最佳回答

这是非常基本的数学。

检查(x 1 - x 0 ) 2 2 2+(y 1 -y0 ) 2 2 > >/supp>2

function inRange(p0, p1, r) {
   r = r || 200;
   var dx = p0.x - p1.x;
   var dy = p0.y - p1.y;

   return (dx * dx + dy * dy) < (r * r);
}

如此称呼它:

if (inRange(player.pos, enemy.pos)) { 
    ...
}

您可以提供第三个备选参数来改变探测半径 。

问题回答

也许您可以使用 Euclidean 距离函数来代替吗? 它会像( player.pos.x - enited.pos.x) x (player.pos.x - enited.pos.x) + (player. pos.y - enited.pos.y) x (player.pos.y - enited.pos.y) = 200 x 200。 抱歉我不知道正方根和正方形函数的语法 。





相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签