简体   繁体   中英

How do I put a height limit within a canvas game?

Right so I'm a bit new to JS and I wanted to know how to put a roof or height limit within this small canvas game. It's practically W3's code but the teacher told us to just model after it. I wanted to fix the annoying issue of just jumping over the map to avoid obstacles.

I don't really know what to try since the height is set by canvas. I tried to make a new function based of hitBottom() which failed.

Just wanted to put the roof or height limit. Here's the original source: Here . Everything is literally the same except colors.

What you want to do is see if the current y-position is lower than 0, since that would be the 'roof' of the room. If the player y position is lower than 0, reset it back to 0, and stop the acceleration.

    this.hitTop = function() {
        if (this.y < 0) {
            this.y = 0;
            this.gravitySpeed = 0;
        }
    }

And to the newpos function, you want to call this function, so add this:

this.hitTop();

Check for y position in newPos method after increasing the y position. If it is less than 0 then make it 0 . Code should look like below;

this.newPos = function() {
    this.gravitySpeed += this.gravity;
    this.x += this.speedX;
    this.y += this.speedY + this.gravitySpeed;

    /* Add below 4 lines */
    if (this.y <= 0) {
        this.y = 0;
        this.gravitySpeed = 0;
    }
    /* Add above 4 lines */

    this.hitBottom();
}

Happy coding ;)

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