Javascript HTML5 Canvas Mario Bros NES克隆,碰撞和跳跃破碎

时间:2013-09-24 23:40:39

标签: javascript html5 canvas

我希望有人能够查看我为一个简单的老式Mario克隆工作的这个javascript代码。 我从几个教程拼凑了我对画布的了解,我无法通过块或跳跃工作得到正确的碰撞。

跳跃似乎让马里奥在无限循环中反复弹跳,看起来很有趣但不太有利于玩游戏!

       function Player() {
     this.srcX = 0;
     this.srcY = 0;
     this.drawX = gameWidth /2;
     this.drawY = 0;
     this.scaleWidth = 38;
     this.scaleHeight = 50;
     this.width = 48;
     this.height = 60;
     this.speed = 10;
     this.maxJump = 50;
     this.velY = 0;
     this.velX = 0;
     this.isJumpKey = false;
     this.isRightKey = false;
     this.isCrouchKey = false;
     this.isLeftKey = false;
     this.jumping = false;
     this.grounded = false;
    }


    Player.prototype.draw = function(){
      clearPlayer();
      this.checkKeys();
      ctxPlayer.drawImage(
        player,
        this.srcX,
        this.srcY,
        this.width,
        this.height,
        this.drawX,
        this.drawY,
        this.scaleWidth,
        this.scaleHeight);
    };
Player.prototype.checkKeys = function () {


 if(this.isJumpKey){

    if (!this.jumping && this.grounded ) {
        this.jumping = true;
        this.grounded = false;
        this.velY = -this.speed * 2;
    }

 }

 if(this.isRightKey){

   if (this.velX < this.speed) {
            this.velX++;
        }

 }
  if(this.isLeftKey){
  if (this.velX < this.speed) {
            this.velX--;
        }
 }
 if(this.isCrouchKey){
      player1.grounded = true;
      player1.jumping = false;
}


};

这是我现在所处位置的代码:http://codepen.io/AlexBezuska/pen/ysJcI

我非常感谢任何帮助,在此期间我会继续搜索和使用它,但是你可以给出的任何指针,甚至是格式化,原型创建等的建议都非常受欢迎(我对画布和原型)

2 个答案:

答案 0 :(得分:4)

checkKeyDown()checkKeyUp()函数中,您可以检查不同的“跳转”键。来自checkKeyDown()

if (keyID === 74) { //spacebar
    e.preventDefault();

    player1.isJumpKey = true;
}

来自checkKeyUp()

if (keyID === 32) { // spacebar
    player1.isJumpKey = false;
    e.preventDefault();
}

因此checkKeyUp()未正确重置player1.isJumpKey。将它们设置为相同,它对我来说很好。

总的来说,可能值得设置一个对象,该对象包含代码中包含多个实例的所有参数。然后通过引用此对象将它们写入代码中。这样你只需要在一个地方改变它们:

CONSTS = {
    upKeyID: 32,
    etc.
}

// then later:

if (keyID === CONSTS.upKeyID) {
    player1.isJumpKey = false;
    e.preventDefault();
}

答案 1 :(得分:0)

我发现了碰撞问题,我在玩家原型中有x位置和y位置变量名为'drawX'和'drawY',但在碰撞检测功能中,它们只是'x'和'y',现在它有效:http://codepen.io/AlexBezuska/pen/ysJcI w00t!