JavaScript 2D冲突异常

JavaScript 2D collision anomaly

本文关键字:异常 冲突 2D JavaScript      更新时间:2023-09-26

我正在试用JavaScript中的HTML5画布脚本,但在2D碰撞检测方面遇到了问题。我基本上是在检查"玩家"的坐标和我放在屏幕上的盒子的坐标,但出现了一个奇怪的结果。我知道为什么会发生这种事,但我不知道如何解决这个问题。

我的一些代码:

function Arc()
{
    // Coordinates.
    this.x = 540 / 2;
    this.y = 0;
    // Radius
    this.r = 50;
    // Gravity / velicoty.
    this.g = 3;
    this.vy = 15;
    // Bounce.
    this.b = -0;
    this.speed = 20;
    this.max_speed = 20;
    this.friction = 0.03444;
}
Arc.prototype.collision = function()
{
    for(var i = 0; i < game.sprites.length; i++)
    {
        if
        (
            // If the right side of the player is greater than the left side of the object.
            this.x + this.r > game.sprites[i].x &&
            // If the bottom of the player is greater than (meaning lower than) the top of the object.
            this.y + this.r > game.sprites[i].y &&
            // If the left side of the player is greater than the right side of the object.
            this.x - this.r < game.sprites[i].x + game.sprites[i].w &&
            // if the top of the player is greater than (meaning lower than) the bottom of the object.
            this.y - this.r < game.sprites[i].y + game.sprites[i].h
        )
        {
            this.y = game.sprites[i].y - this.r;
            this.vy *= this.b;
        }
    }
}

异常情况是,当我将玩家精灵移动到框的左侧或右侧时,它会在Y轴上向上跳跃,因为上面的逻辑检查总是正确的。显然,这是出乎意料的,因为精灵应该只在发生跳跃时与框的顶部交互。

注意:我不是在寻找一个只在长方体两侧添加碰撞的解决方案(这很简单)。相反,我正在寻找一种解决方案,允许以目前的工作方式在盒子的所有侧面(包括顶部)发生碰撞,但不会出现精灵在触摸盒子时突然跳到盒子顶部的异常情况。

我在JSFiddle上复制了我的整个项目,用于演示(键a、d和空格键):http://jsfiddle.net/h5Fun/

无论这是否是您想要的,它都解决了问题:

this.x = game.sprites[i].x + 150;
this.vx *= this.b;

问题是您在碰撞时设置了不正确的组件。如果希望圆在碰到矩形时停止,而不是在其顶部,请使用x,而不是y

150是矩形的大小。这意味着它将停止在精灵的右侧。由于修改了速度(this.vx),反弹已经存在。