Javascript HTML5 Canvas Mario Bros NES克隆,碰撞和跳跃中断

我希望有人能够看到我为简单的老式Mario克隆产品而努力的javascript代码.
我从几个教程中拼凑出了我对画布的了解,但我无法正确地与块碰撞或跳跃工作.

跳跃似乎使马里奥(Mario)不断地跳来跳去,这看上去很有趣,但不利于玩游戏!

       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;
}


};

这是我现在所在的codepen:http://codepen.io/AlexBezuska/pen/ysJcI

我非常感谢您的帮助,在此期间我将继续搜索并尝试使用该工具,但是您可以提供的任何指针,甚至是有关格式设置,原型创建等的建议,都非常感激(对于画布和原型,我都是新手)

解决方法:

在您的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();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。