碰撞检测:圆形物体 [英] Collision detection : rounded object

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

问题描述

我正在开发一个Java游戏(但开发语言并不重要),包括圆形物体,如球或冰球,现在正在进行碰撞。
我使用计时器,所以在每一帧我检查是否发生碰撞。

I'm developing a Java game (but the dev. language doesn't really matter) including rounded objects like balls or pucks, and now working on collisions. I use a timer, so on every frame I check if a collision happens.

这是一个代表对象右上角的图形。

Here is a graph that represents the top-right piece of an object.

对象的中心由点[0,0]表示,其半径为10px,单位为像素。

The center of the object is represented by the point [0,0], its radius is 10px and the units are pixels.

现在,如果我的对象(例如, obj_1 )是方形/菱形(蓝线),则查找另一个( obj_2 )碰撞它我只需得到它们的坐标并检查 Math.abs(obj_1.x - obj_2.x)+ Math.abs(obj_1.y - obj_2.y)< ; = radius 我会知道是否发生碰撞。

Now if my object (for example, obj_1) is square/diamond-shaped (blue line), to find if another one (obj_2) collides it I just have to get their coordinates and by checking Math.abs(obj_1.x - obj_2.x) + Math.abs(obj_1.y - obj_2.y) <= radius I will know if there is a collision.

但问题是圆形(红线)更棘手,因为它需要更多的空间,这个占用的空间不受直线的限制。当然我必须舍入一些值(例如在上图中,如果我想在 x = 2 检查碰撞,我将必须舍入y值,看起来像9.5到10)。但我根本不知道如何获得这个公式。任何帮助都将非常感激。

But the problem is more tricky with a circle shape (red line), because it takes more space and this occupied space is not bounded by a straight line. Of course I will have to round some values (for example in the previous graph, if I want to check a collision at x = 2 I will have to round the y value which looks like 9.5 to 10). But I simply have no idea of how to get this formula. Any help will be very appreciated.

推荐答案

正如您提到的实现语言无关紧要,我将为您提供通用解决方案用于检测圆形物体的碰撞。

As you mentioned that the implementation language does not matter, I will give you a generic solution for detecting collision of round objects.

此外,从我收集的内容来看,场景中的所有物体都是圆圈。以下解决方案不适用于检测圆形与其他形状之间的碰撞。

Also, from what I gather, all the objects in the scene are circles. The solution below does not apply for detecting collision between a circle and some other shape.

假设您有两个圆 c1 c2 即可。假设相应的半径为 c1.r c2.r ,且中心为(c1.x,c1.y)(c2.x,c2.y),然后以下函数将判断c1和c2是否发生碰撞

Suppose you have two circles c1 and c2. Suppose the corresponding radii are c1.r and c2.r, and the centers are (c1.x,c1.y) and (c2.x, c2.y), then the following function will tell whether c1 and c2 are in collision

boolean areColliding(Circle c1, Circle c2){

   center_distance = sqrt((x1-x2)^2 +(y1-y2)^2);  //this is the distance between the centers of the two circles.

  if((c1.r+c2.r) < center_distance)
           return false;
  else
          return true;

}

此伪代码函数将返回 true 如果圆圈发生碰撞,否则为假。

This pseudo-code function will return true if the circles are colliding, false otherwise.

基本上,该功能的作用是检查圆心之间的距离是否大于他们各自的半径。

Basically, what the function does is check whether the distance between the centers of the circles is greater than the sum of their respective radius.

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

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