我无法处理JavaScript冲突。您应该如何检查它们?

时间:2019-06-27 22:00:15

标签: javascript jquery html html5-canvas physics

我一直在用JS开发一个小型物理游戏,在该游戏中,您使用一个块移动其他块,然后它们碰撞。我的碰撞有时会停止,我也不知道为什么。我也不确定是否要检查它们的正确方法。

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);
}

Fiddle is Here

1 个答案:

答案 0 :(得分:0)

如果设置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; } ,则在给出的示例中您的碰撞检测代码似乎可以正常工作。如果您的目标是使两个物体在碰撞时交换速度,则以下方法将有所帮助:

temp

这简单地交换了速度而没有取反(请注意临时{{1}}变量),这会导致碰撞正常进行,并使对象沿相反的方向移动。如果要使用适当的动量,可以尝试调整代码以使用相关的公式。