当项目的 Y 在 JS 中为 0 时,碰撞检测条件不起作用

Collision detection conditions not working when the item's Y is 0 in JS

在代码中,我试图模拟一个球在 x 方向上的速度运动以及二维世界中的重力运动。一切似乎都正常,球一直弹跳直到它到达地面,然后与那个盒子的壁碰撞检测的条件将不起作用,球滚出屏幕。

我已经在这个 link 中分享了完整的代码:https://jsfiddle.net/tahajalili/bhqurw5g/3/ 我是这个领域的新手,所以有人可以帮助我吗?

但是JavaScript代码是这样的:

var canvas = document.getElementById('gameScreen');
var ctx = canvas.getContext('2d');

//world 
var width = 800;
var heigth = 800;
var gravity = 9.8;
var fps = 1/40;
var e = 0.8;

//Object
function Ball(x, y, velocity, dy, radius, mass, color){
    this.x = x;
    this.y = y;
    this.vy = velocity;
    this.vx = velocity;
    this.dy = dy;
    this.mass = mass;
    this.r = radius;
    this.color = color;
    
    this.update = function(){
        var ay = gravity;
        if(this.y + radius > heigth){
            this.vy = -this.vy;
            this.vy *= e;            
        }
        else if(this.x + this.r > width){
            this.vx = -this.vx;
        }
        else if (this.x - this.r < 0) {
            this.vx = -this.vx;
        }        
        else{
            this.vy += ay * fps;            
        }
        this.y += this.vy *fps*100;
        this.x += this.vx;
        this.draw();
    }

    this.draw = function(){
        ctx.beginPath();
        ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false);
        ctx.fillStyle = this.color;
        ctx.fill();
        ctx.stroke();
        ctx.closePath();
    }  
}

//working functions
function init(){
    b = new Ball(30, heigth-500, 7, 1, 30, 0.1, 'red');
}

function animate(){
    requestAnimationFrame(animate);
    ctx.clearRect(0,0,width,heigth);
    b.update();
}

init();
animate();

您使用 else if.

让正确的碰撞测试依赖于地板碰撞测试

如果你给谓词贴上标签,你可能就不会犯那个错误了

this.update = function () {
    const floorCollision = this.y + this.r > heigth;
    const rightCollision = this.x + this.r > width;
    const leftCollision = this.x - this.r < 0
    const xCollision = rightCollision || leftCollision;

    if (floorCollision) {
        this.vy *= -1;
        this.vy *= e;
    } else {
        this.vy += gravity * fps;
    }

    if (xCollision) {
        this.vx *= -1;
    }

    this.y += this.vy * fps * 100;
    this.x += this.vx;

    this.draw();
}