简体   繁体   中英

Collision detection with JavaScript and HTML5 canvas

I have a problem with collision detection in my 2D game. 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:

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.

You have a typo: objekt should be 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
)){ ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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