[英]I can't get my JavaScript collisions to work. How should you check for them?
I have been working on a small physics game in JS where you use a block to move other blocks and they collide. 我一直在用JS开发一个小型的物理游戏,在该游戏中,您使用一个块移动其他块并使它们碰撞。 My collisions sometimes stop working, and I do not know why.
我的碰撞有时会停止,我也不知道为什么。 I'm also not sure if I'm checking for them the correct way.
我也不确定是否要检查它们的正确方法。
this.checkCollision = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright)) {
crash = false;
}
if (crash) {
this.colliding = true;
$('body').css('background-color', 'red');
this.collide(otherobj);
// this.x++;
} else {
$('body').css('background-color', 'white');
this.colliding = false;
}
return crash;
}
this.collide = function(otherobj) {
//for when they stick
if (this.speedX < 0.1 && this.speedY < 0.1) {
this.x -= 2;
otherobj.x += 2;
}
//get speed of x
otherobj.speedX = this.speedX;
this.speedX = -((this.mass * this.speedX) + (otherobj.mass * otherobj.speedX)) / (this.mass + otherobj.mass);
// get speed of y
otherobj.speedY = this.speedY;
this.speedY = -((this.mass * this.speedY) + (otherobj.mass * otherobj.speedY)) / (this.mass + otherobj.mass);
}
Your collision detection code seems to work in the example given if you set blueGamePiece.speedX = -5
. 如果设置
blueGamePiece.speedX = -5
则碰撞检测代码在给定的示例中似乎可以使用。 If your goal is to make the two bodies exchange velocities when they collide, the following will help: 如果您的目标是使两个物体在碰撞时交换速度,则以下方法将有所帮助:
this.collide = function (otherobj) {
// swap X speeds
temp = otherobj.speedX;
otherobj.speedX = this.speedX;
this.speedX = temp;
// swap Y speeds
temp = otherobj.speedY;
otherobj.speedY = this.speedY;
this.speedY = temp;
}
This simply swaps the velocities without negating (notice the temporary temp
variables), which causes the collisions to work fine, and for the objects to move in opposite directions. 这样就可以简单地交换速度而不会取反(请注意临时的
temp
变量),这会使碰撞正常进行,并使对象沿相反的方向移动。 If you want to use proper momentum, you can try to adjust the code to use the relevant formulae. 如果要使用适当的动量,则可以尝试调整代码以使用相关公式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.