Javascript:碰撞检测 [英] Javascript: Collision detection

查看:162
本文介绍了Javascript:碰撞检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我理解碰撞检测在JS中的工作原理吗?我不能使用jQuery或gameQuery - 已经使用原型 - 所以,我正在寻找一些非常简单的东西。不要求完整的解决方案,只需指出正确的方向。

could someone please help me to understand how collision detection works in JS? I can't use jQuery or gameQuery - already using prototype - so, I'm looking for something very simple. Not asking for complete solution, just point me to the right direction.

假设有:

<div id="ball"></div>
and 
<div id="someobject0"></div>

现在球正在移动(任何方向)。 Someobject(0-X)已经预先定义,其中有20-60个随机定位如下:

Now the ball is moving (any direction). "Someobject"(0-X) is already pre-defined and there's 20-60 of them randomly positioned like this:

#someobject {position: absolute; top: RNDpx; left: RNDpx;} 

我可以使用someobject(X)位置和测试碰撞创建一个数组而球正在移动...类似于:

I can create an array with "someobject(X)" positions and test collision while the "ball" is moving... Something like:

for(var c=0; c<objposArray.length; c++){
........ and code to check ball's current position vs all objects one by one....
}

但我想这将是一个noob解决方案,它看起来很慢。
还有什么更好的吗?

But I guess this would be a "noob" solution and it looks pretty slow. Is there anything better?

推荐答案

首先要做的是检测你是否有球与物体之间的碰撞。

The first thing to have is the actual function that will detect whether you have a collision between the ball and the object.

为了表现,实施一些粗略的碰撞检测技术会很棒,例如边界矩形,如果需要检测到碰撞,则更精确一个,这样你的函数运行起来会更快一些,但使用完全相同的循环。

For the sake of performance it will be great to implement some crude collision detecting technique, e.g., bounding rectangles, and a more accurate one if needed in case you have collision detected, so that your function will run a little bit quicker but using exactly the same loop.

另一个有助于提高性能的选项是使用您拥有的对象进行一些预处理。例如,您可以将整个区域分解为像通用表格一样的单元格,并存储特定单元格中包含的相应对象。因此,要检测碰撞,您将检测球占据的细胞,从这些细胞中获取物体并使用碰撞检测功能。

Another option that can help to increase performance is to do some pre-processing with the objects you have. For example you can break the whole area into cells like a generic table and store the appropriate object that are contained within the particular cells. Therefore to detect the collision you are detecting the cells occupied by the ball, get the objects from those cells and use your collision-detecting function.

为了加快速度,你可以实现 2d-tree quadtree R-tree

To speed it up even more you can implement 2d-tree, quadtree or R-tree.

这篇关于Javascript:碰撞检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆