检测多个物体之间的碰撞的正确方法是什么?
这是我在大学作业中尝试做的事情,我对此还很陌生,但我已经阅读了很多关于这个主题的文章。请有人用最简单的术语解释一下如何做我想做的事情,以便我能够理解需要发生什么?
我有一个对象数组,每个对象在屏幕上画一个圆圈;我让它们在边界框中弹跳,但现在我希望它们发生碰撞。
我写了下面的方法,它有效……但只是有效。这些球偶尔会被卡住并相互“抖动”,我不知道为什么会发生这种情况。另外,我认为我正在检查不必要的碰撞(?)。
void handleObjectCollision() {
for(int i = 0; i < _myBtns.length; i++) {
if(i != _id) {
float dx = _myBtns[i].x - x;
float dy = _myBtns[i].y - y;
float distance = sqrt(dx*dx + dy*dy);
if(distance < r * 2) {
xS = -xS;
yS = -yS;
// Debug
// println("Collision!");
}
}
}
我的课程和相关片段的完整粘贴可以在这里找到:http://pastebin.com/eJawiHAE。
另外,这是我一直在使用的一个示例, http://processing.org/learning/主题/bouncybubbles.html。
我试图实现一个简单的弹跳(速度反转?),而不添加物理或使用向量,因为我希望能够首先以最简单的形式理解正在发生的事情。
谢谢。
This is something I'm trying to do for a university assignment and I'm quite new to it, but I've done a lot of reading on the subject. Please could someone to explain, in the simplest terms, how to do what I'm trying to do, so that I can understand what needs to happen?
I have an array of objects, each draw a circle to the screen; I have them bouncing within a bounding box but now I'd like them to collide.
I wrote the method below, which is working... but only just. The balls occasionally get stuck and 'jitter' on one another and I have no idea why this is happening. Also, I think I'm checking for more collisions than necessary(?).
void handleObjectCollision() {
for(int i = 0; i < _myBtns.length; i++) {
if(i != _id) {
float dx = _myBtns[i].x - x;
float dy = _myBtns[i].y - y;
float distance = sqrt(dx*dx + dy*dy);
if(distance < r * 2) {
xS = -xS;
yS = -yS;
// Debug
// println("Collision!");
}
}
}
A full paste of my class and pertaining segments can be found here: http://pastebin.com/eJawiHAE.
Also, here is an example I've been working from, http://processing.org/learning/topics/bouncybubbles.html.
I'm trying to achieve a simple bounce (reversal in speed?), without added physics or using vectors, as I want to be able to understand what's happening in it's simplest form, first.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能仅仅反转物体移动的方向,因为碰撞可能几乎从它的后面发生,在这种情况下,反转将使其再次与与其碰撞的物体发生碰撞。这解释了您看到的抖动。您需要考虑碰撞发生的方向,并使用物理学中所谓的“弹性碰撞”的相关物理公式相应地调整方向矢量。
在这里,检查一下:http://en.wikipedia.org/wiki/Elastic_collision
You cannot just reverse the direction in which your object is moving, because the collision may happen almost from behind it, in which case the reversal will put it again in collision course against the object which collided with it. That explains the jitter that you see. You need to consider the direction from which the collision occurred, and adjust your direction vector accordingly, using the related physics formulas for what is known in physics as "elastic collisions".
Here, check this out: http://en.wikipedia.org/wiki/Elastic_collision