gravity inside html5 canvas

橙三吉。 提交于 2019-12-31 05:18:09

问题


I'm trying to do a copy of the original super mario game using html5 canvas just for fun and to learn more about the canvas tool and it's animation but i am stuck at making Mario do it's jump here is my jsfiddle : http://jsfiddle.net/2tLCk/1/

how should i fix my up function to make mario jump and return back to the ground like in this website http://blog.nihilogic.dk/ i tried to understand it's code but i couldn't ?

if (keydown.up) {

            vy += gravity;
            character.CurentPos = 11;
            character.x += character.speed;
            character.y += vy;

        }

回答1:


Here's a jumping Mario http://jsfiddle.net/2tLCk/22/.

If jumping is 1 - going up. If jumping is 2 - going down.

if(jumping){
     if(jumping == 1) {
          if(character.y > 140) character.y -= gravity;
          else jumping = 2;
     } else if(jumping == 2) {
          if(character.y < 184) character.y += gravity;
          else{
               character.y = 184;
               jumping = false;
               character.CurentPos = 6;
          }
     }
}else if(keydown.up) {
    jumping = 1;
    character.CurentPos = 11;
}

And you would probably want to use this https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame instead of setInterval().




回答2:


You basically want the gravitiy to be always active, not only when pushing the down key. When jumping (key up) you have to add to vy. Like this:

    if(keydown.up) {
         vy += -2;   
    }
    vy += gravity;
    if(character.y > 184) { // simple collision detection for ground floor
        vy = 0;
        character.y = 184;
    }
    //character.CurentPos = 11;
    //character.x += character.speed;
    character.y += vy;

see http://jsfiddle.net/pjQb3/




回答3:


I would do something like this:

// Global forces
character.vy += gravity;

// User input
if (keydown.up) {
  character.vy += -2;
}

// Final location
if (character.y + character.vy >= 184) {
  // Update player location.
  character.y += character.vy;
} else {
  // Player was about to move past ground so place player directly on ground
  // and reset velocity.
  character.y = 184;
  character.vy = 0;
}


来源:https://stackoverflow.com/questions/21204001/gravity-inside-html5-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!