微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

我在此链接分享了完整代码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,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,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();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。