javascript - 您如何在 JavaScript 游戏中编写跳跃代码?
问题描述
我第一次用 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; }
检查用户是否登陆
推荐阅读
- css - 在样式化组件中使用 `css` 函数会导致性能下降吗?
- robocopy - 在“仅报告”模式下运行 Robocopy
- python - 绘制与 matplotlib 交错的 numpy 数组
- go - 在 Go 中创建一个 C 结构数组
- python - Django ORM查询从一个表中检索对象以及另一个与外键相关的表中的最新对象?
- recursion - Prolog:将数字拆分为递增整数的序列
- python - 在每个单元完成后让 jupyter nbconvert 将输出写入笔记本,而不是等到执行结束
- python - 在python中按日期和总和值对非唯一日期时间列进行分组
- c# - 使用 AJAX 删除 Razor 页面
- scala - 如何从scala数据框中的数组列访问值