2011-08-26 117 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