我希望有人可以看一下我为简单的老式Mario克隆产品而努力的javascript代码。
我已经从几个教程中拼凑出了我对 Canvas 的了解,但我无法与块碰撞或跳跃正常工作。
跳跃似乎使马里奥(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
我非常感谢您的帮助,在此期间我将继续搜索并尝试使用该工具,但是您可以提供的任何指针,甚至是有关格式设置,原型(prototype)创建等的建议,都非常感激(对于 Canvas 和原型(prototype),我都是新手)
最佳答案
在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();
}