我建立一个物理引擎作为学习经验,当涉及到不同碰撞和解析功能的可靠实现时,我有点卡住了。它的数学运算没有问题,而是如何检查它。
我有盒子,椭圆,线等的单独对象,这些对象都来自父物质实体'对象,但有一些自己的属性,如他们的形状。有点像这样:
function PhysicsEntity(x, y) {
this.x = x || 0;
this.y = y || 0;
this.velocity = {
x: 0,
y: 0
}
}
function Box(x, y, width, height) {
PhysicsEntity.apply(this, [x, y]);
this.width = width || 150;
this.height = height || 50;
this.shape = 'box';
}
现在,当两个物体彼此靠近时,我想检查它们是否实际碰撞,但为了做到这一点,我需要为每种形状组合计算一些不同的东西(盒子和盒子,盒子和放大器) ;椭圆,椭圆和线等)
我的一种方法是将两个形状放在一个数组中,按字母顺序排序,连接它并将其用作一个充满函数的对象的键:
var collisions = {
'box_ellipse': function() {
// Collision check
}
}
isColliding(Entity1, Entity2) {
var shapes = [Entity1, Entity2];
if(Entity1.shape.localCompare(Entity2.shape) > 0) {
entities.reverse();
}
collisions[entities[0] + '_' + entities[1]]();
}
虽然这有效,但感觉真的黑客攻击和脆弱。
因此,简而言之,我基本上寻找一种优雅的方式来调用一个函数或类似的东西,基于两个随机排序的未知值,如果/切换代码不会涉及十几行意大利面。< / p>
答案 0 :(得分:0)
var collisions = {
'box_ellipse': function(box, ellipse) {
// Collision check
}
// other combos here
}
isColliding(Entity1, Entity2) {
var s1 = Entity1.shape;
var s2 = Entity2.shape;
if(collisions[s1 + '_' + s2] !== undefined) // the collision function exists
collisions[s1 + '_' + s2](Entity1, Entity2); // call it on the entities in order
else // they must be reversed
collisions[s2 + '_' + s1](Entity2, Entity1);
}
注意:所有组合(忽略顺序)都应在collisions
对象中定义。如果可能的形状为:"box"
,"circle"
,"triangle"
,则collisions
对象应包含6个键:
box_triangle
或triangle_box
box_circle
或circle_box
circle_triangle
或triangle_circle
box_box
circle_cirlce
triangle_triangle
密钥shapeA_shapeB
的函数将接受两个实体作为参数:shapeA
之一和shapeB
中的另一个,然后检查两个实体的冲突。