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

2F33T

我第一次用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();

告诉我是否需要更多信息

拉涅利

跳跃后,除非玩家到达地面,否则无法跳跃。

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

如果这样,我将在此添加另一个比较:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章