繁体   English   中英

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

[英]How do you code jumping in a javascript game?

我第一次在 javascript 中编写游戏,我的大部分代码效率不高。 我被困在如何为我的立方体(我的游戏角色)编写跳跃方法。 跳跃有效,但玩家可以二段跳。 如果用户再次按下跳转键,则在向下的途中发生双跳。 我尝试设置一个变量,当玩家在地面上时将修改该变量,如果它是真的,那么你只允许跳跃,但它没有工作。 这是代码:

    //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; } if(event.keyCode == 38 && player.jump == false && player.isOnGround()){ player.jump = true; }检查用户是否登陆

暂无
暂无

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

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