如何在JavaScript游戏中编写跳跃代码?

3

我第一次用JavaScript编写游戏,大部分的代码都不够高效。现在我卡在了如何为我的方块(游戏角色)编写跳跃方法上。跳跃是可以实现的,但玩家可以二连跳。如果用户再次按下跳跃键,则会在下落时进行二连跳。我尝试设置一个变量,在玩家落地时修改此变量,如果变量值为true,则只允许跳一次,但这并没有奏效。以下是代码:

    //setting screen up
const canvas = document.getElementById('canvas');
const c = canvas.getContext('2d');
canvas.width = innerWidth;
canvas.height = innerHeight;

//ground
gHeight =  canvas.height/1.3
function ground(){
    c.fillStyle = 'white';
    c.fillRect(0,gHeight,canvas.width,canvas.height-gHeight);
}
//player
class Player{
    constructor(x,y,w,h){
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.color = 'rgb(92,168,255)';
        this.l = false;
        this.r = false;
        this.speed = 10
        this.hp = 100;
        this.jump = false;
        this.jumpC = 0;
    }
    draw(){
        c.fillStyle = this.color;
        c.fillRect(this.x,this.y,this.w,this.h);
    }
    update(){
        this.draw();
        //gravity
        if(this.y < gHeight - this.h){
            this.y += 5;
        }
        //movement
        if(this.l == true){
            this.x -= this.speed;
        }
        if(this.r == true){
            this.x += this.speed;
        }
        //jump
        if(this.jump == true){
            this.y -= 10;
            this.jumpC += 5;
        }
        if (this.jumpC >= 100){
            this.jump = false;
            this.jumpC = 0;
        }
    }
}
var player = new Player(100, 100,50,50);
//main loop
var animationId;
function animate(){
    c.fillStyle = 'rgba(0,0,0,0.7)';
    c.fillRect(0,0, canvas.width, canvas.height);
    animationId = requestAnimationFrame(animate);
    
    //drawing the ground
    ground();
    //drawing the player
    player.update();
    //ending game
    if(player.hp == 0){
        cancelAnimationFrame(animationId);
    }
}
//keypress
addEventListener('keydown', (event)=>{
    if(event.keyCode == 37) {
        player.l = true;
    }
    if(event.keyCode == 39) {
        player.r = true;
    }
    if(event.keyCode == 38 && player.jump == false){
        player.jump = true;
    }
});
//keyup
addEventListener('keyup', (event)=>{
    if(event.keyCode == 37 ) {
        player.l = false;
    }
    if(event.keyCode == 39) {
        player.r = false;
    }
});
animate();

告诉我是否需要更多信息。

可能重复 https://dev59.com/4mLVa4cB1Zd3GeqPtzDZ - MRRaja
@MRRaja 我确实看过这篇帖子,我用了它的代码来实现跳跃机制,但用户可以在下落的路上跳跃。 - m.said
关于这篇帖子,有什么想法? - FZs
1个回答

3

使跳跃在玩家落地前不可能再次跳跃。

if(event.keyCode == 38 && player.jump == false){ player.jump = true; }

我会在这个条件语句中加入另一个判断:

if(event.keyCode == 38 && player.jump == false && player.isOnGround()){ player.jump = true; }以检查用户是否着陆。


我会尝试这个,看看它是否有效,并告诉您结果或任何新的进展。 - m.said

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接