一旦检测到碰撞,我就会尝试标准化两个球之间的距离
碰撞检测
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;
},
因此,一旦我们确定这些球体发生碰撞,我就需要重置它们彼此之间的距离...我会回想起我在代数课上使用点/斜率公式等的日子...
我已经得到了它们之间需要存在的所需距离以及(我认为的)碰撞 Angular 。
我需要在碰撞 Angular 上设置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 =
}
最佳答案
思考向量。如果两个形状重叠,则会得到一个从一个形状的中心到另一个形状的中心的向量,如下所示(这只有在将它们的速度添加到它们的位置后才有意义,因为那时它们就会重叠):
var diff = {
x: next_shape.x - shape.x,
y: next_shape.y - shape.y
};
这是从 shape
到 next_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
的正/负方向,以便它们在碰撞后继续沿该轨迹运行(如果它们确实保持速度的话)。
请注意,这并不真正使形状彼此“弹跳”,而只是将它们移开足够远以解决它们开始重叠后存在的重叠问题。所以说还是比较简单的。但是有大量的资源可以为您提供更精确的碰撞检测和碰撞响应方法。
关于javascript - 标准化球之间的距离(碰撞后) - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7200403/