繁体   English   中英

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

[英]Javascript HTML5 Canvas Mario Bros NES clone, collisions and jumping broken

我希望有人能够看到我一直在为一个简单的老式马里奥克隆工作的这个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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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