2011-08-26 112 views
0

我想一旦碰撞被检测规范化距离(后碰撞) - JavaScript的

正常化两个球之间的距离,碰撞检测

do_shapes_collide: function(shape1,shape2) 
{ 
    var reach1 = shape1.radius + shape1.velocity() + vr.o.border_width; 
    var reach2 = shape2.radius + shape2.velocity() + vr.o.border_width; 

    var distance = vr.distance(shape1, shape2); 

    return distance < reach1 + reach2; 

}, 

所以一旦我们确定这些球体相互碰撞,我需要重新设置彼此之间的距离......我用代表点/斜率公式等的代数类获得了闪回......

我已经得到了需要的距离,需要存在于他们和(我相信是的)之间碰撞角度。

我需要设置shape x/y上的碰撞角度。

我应该从这里做的设置shape的X和Y什么一片空白......

if (vr.do_shapes_collide(shape, next_shape)) 
{ 
    var req_distance = shape.radius + next_shape.radius + (vr.o.border_width * 2); 
    var slope = (shape.y - next_shape.y)/(shape.x - next_shape.x); 
    shape.x = 
    shape.y = 
} 

回答

3

想想载体。如果你有两个形状是重叠的,你就有一个从一个中心到另一个中心的向量,这样做只有在它们的速度加到它们的位置后才有意义,因为那时它们会重叠):

var diff = { 
    x: next_shape.x - shape.x, 
    y: next_shape.y - shape.y 
}; 

这是从shapenext_shape载体。而且它的尺寸较小(它更短)比它需要让形状保持分开。因此,要找到形状需要移动

var diff_magnitude = Math.sqrt(diff.x*diff.x + diff.y*diff.y); 
var overlap = (req_distance - diff_magnitude)/2; // each shape needs to move this distance 

现在缩放diff矢量观看比赛的距离/幅度

diff.x = overlap * diff.x/diff_magnitude; 
diff.y = overlap * diff.y/diff_magnitude; 

的最后,在一个方向上移动一个形状的量,和其它形状在相反的方向

shape.x -= diff.x; 
shape.y -= diff.y; 
next_shape.x += diff.x; 
next_shape.y += diff.y; 

两个形状现在应该正好相互对立起来。

您还需要将它们的速度设置为diff的正/负方向,以便它们在碰撞后继续在该轨迹上(如果确实它们保持其速度)。

请注意,这并不是真正“反弹”彼此的形状,而只是将它们移开足够的距离以解决重叠之后存在的重叠。所以它很简单。但是有很多资料可以为您提供更精确的碰撞检测和碰撞响应方法。

+0

你是一位圣人,不仅我有我的答案,但我真正理解它。 – jondavidjohn