[英]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.