现在,我正在尝试将响应应用于我的SAT、Circle - Poly和Poly - Poly碰撞检测。我将这篇文章中的代码移植到了JavaScript中:
http://rocketmandevelopment.com/blog/separation-of-axis-theorem-for-collision-detection/
现在,检测可以应用于所有类型,但响应失败了,并以疯狂的速度和错误的角度进行运动,它不依赖于对象的质量(使用面积平方而不是质量)且角速度未被应用。
JSFiddle(模拟中未应用重力,请使用箭头键移动),JS中的第一部分是向量,然后是物理学,最后是主函数。
这是我对形状的定义:(为“JSFiddle”链接添加了一些代码:P)
var Circle = function(body, c, r, cor, cof) {
this.body = body // Static or dynamic
this.c = c; // Center
this.r = r; // Radius
this.m = getCMass(r); // Mass = Area
this.v = new Vector(); // Velocity
this.cor = cor; // Coefficient of restitution
this.cof = cof; // Coefficient of friction
this.a = 0; // Angle
this.av = 0; // Angular velocity
this.type = "Circle";
}
var Polygon = function(body, c, vs, cor, cof) {
this.body = body // Static or dynamic
this.c = c; // Center
this.vs = vs; // Vertices
this.m = getPMass(vs); // Mass = Area
this.v = new Vector(); // Velocity
this.cor = cor; // Coefficient of restitution
this.cof = cof; // Coefficient of friction
this.a = 0; // Angle
this.av = 0; // Angular velocity
this.type = "Polygon";
}
function getCMass(r) { // More like, getCArea
return (r * r * Math.PI);
}
function getPMass(vs) {
var area = 0;
var j = vs.length - 1;
for (var i = 0; i < vs.length; i++) {
area += (vs[j].x + vs[i].x) * (vs[j].y - vs[i].y);
j = i;
}
return (area / 2);
}
所有碰撞函数都会给出失败的响应结果,因此一定存在某种连接。
回到角速度问题,我知道如何旋转多边形,但我想在碰撞后得到新的角速度:
px = x * cos(a) - y * sin(a);
py = x * sin(a) + y * cos(a);
还有,我制作了一个很不错的物理模拟器,可以模拟线条和贝塞尔曲线,这可能会有所帮助:http://murplyx.net/projects/csb/
对我来说最重要的部分是如何修复速度根据速度和角度正确地进行计算的问题?(我使用向量而不是三角函数-.-)然后我可以考虑质量和角速度。谢谢。我避免使用Box2D盒子。
编辑:添加了计算面积^2以设置质量相等的函数。