我无法让我的 JavaScript 冲突工作。你应该如何检查它们?



我一直在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);
}

小提琴在这里

如果您设置blueGamePiece.speedX = -5,则在给出的示例中似乎可以使用。如果您的目标是在碰撞时将两个尸体交换速度,则以下会有所帮助:

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变量(,这会导致碰撞正常工作,并使对象朝相反的方向移动。如果要使用适当的动量,则可以尝试调整代码以使用相关公式。

最新更新