我正在尝试创建一个程序,在该程序中,具有动量的球会与固定的倾斜表面精确碰撞。虽然我相信自己能够找到两个物体之间的碰撞点,但我无法每次都能以正确的方式使球从倾斜的表面反弹。我当前的碰撞代码是:
Rect.prototype.collide = function(ent) {
//Slope of the line
var ang = Math.atan2((this.y2 - this.y1), (this.x2 - this.x1));
//Angle of the ball's momentum
var ballAng = Math.atan2(ent.g, ent.velx);
//Angle of the line perpendicular to the line
var angt = ang + Math.PI / 2 * (ent.g < 0 ? -1 : 1);
//The angle of reflection
var finAng = ang - (ballAng - ang);
//Finds where along the first line passed the collision occurs. If the returned output is above 1 or below 0, no collision occurs.
var colTime = findInt({
x1: ent.lastFrame[0] + Math.cos(angt) * ent.r,
y1: ent.lastFrame[1] + Math.sin(angt) * ent.r,
x2: ent.x + Math.cos(angt) * ent.r,
y2: ent.y + Math.sin(angt) * ent.r
}, {
x1: this.x1,
x2: this.x2,
y1: this.y1,
y2: this.y2
}, 2);
//The ball will collide with the line if it passes over it on this frame.
if(colTime > 0 && colTime < 1) {
//If a collision occurs, I set the ball back to the point when it collided.
ent.lastFrame = [ent.x, ent.y];
ent.x -= ent.velx * (1 - colTime);
ent.y -= ent.g * (1 - colTime);
//And bounce it off at the angle of reflection
var totVel = Math.pow(Math.pow(ent.velx, 2) + Math.pow(ent.g, 2), 1 / 2);
totVel *= 0.9;
ent.velx = Math.cos(finAng) * totVel;
ent.g = Math.sin(finAng) * totVel;
//After changing the angle, I use any momentum that I removed and transfer it to the new momentum.
ent.x += ent.velx * (1 - colTime);
ent.y += ent.g * (1 - colTime);
}
};
ent是球对象。在每次更新球的位置之前,将球的lastFrame属性更新为具有球的x和y坐标的数组。球的x和y属性当然是坐标。 r属性是半径,而velx和g属性分别是水平和垂直动量。我不认为每次反射的角度都是准确的,并且如果球的动量太小或以太接近线的角度并下坡的角度运动,则球会通过线。我仔细检查了一下并编辑了此代码,但是我的愚蠢似乎阻止了我。我将不胜感激任何输入或帮助!找到我当前的项目here。我尚未实施轮换。现在,我只是想使球正确反弹。
编辑:找到答案。我像白痴一样根据球的垂直动量来改变垂直线的角度。