简体   繁体   English

使用JavaScript和HTML5 canvas进行碰撞检测

[英]Collision detection with JavaScript and HTML5 canvas

I have a problem with collision detection in my 2D game. 我在2D游戏中遇到碰撞检测问题。 The collision is good at top and left of the object but doesn't work as expected at bottom and right of the object. 碰撞在对象的顶部和左侧很好,但在对象的底部和右侧却无法正常工作。 How can I fix it? 我该如何解决?

Javascript: Javascript:

this.isPlayerCollideWith = function(object) {

    if (this.posX < objekt.posX + object.width && this.posX + this.width  > object.posX &&
        this.posY < object.posY + object.height && this.posY + this.height > object.posY) {

        //up
        if(this.posY < objekt.posY + object.height){
            this.posY -= this.speed;
        }
        //down
        if(this.posY + this.height > object.posY){
            this.posY += this.speed;
        }

        //left
        if(this.posX < object.posX + object.width){
            this.posX -= this.speed;
        }

        //right
        if(this.posX + this.width > object.posX){
            this.posX += this.speed;
        }

    }
};

All of my code is running through an HTML5 canvas. 我所有的代码都通过HTML5画布运行。

You have a typo: objekt should be object . 你有一个错字: objekt应该object

You're collision logic might be (might not be) off also. 您的碰撞逻辑可能也(可能不会)关闭。 Here's working code: 这是工作代码:

if(!(
    this.x             > object.x+object.width  ||
    this.x+this.width  < object.x           ||
    this.y             > object.y+object.height ||
    this.y+this.height < object.y
)){ ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM