简体   繁体   English

游戏:方形不会落在画布小提琴中javascript,html5

[英]game: square doesnt fall in canvas fiddle javascript, html5

I'm creating this jumping game 我正在创建这个跳跃游戏

PROBLEM 问题

Withing the jumping logic I add Player.y +=Player.vy; 通过跳转逻辑,我添加了Player.y +=Player.vy; to make the red square fall once reached the higher level (simulating gravity), but it just get stucked at the top. 使红色方块掉落到更高的高度(模拟重力),但只是卡在顶部。 https://jsfiddle.net/0f34at75/6/ https://jsfiddle.net/0f34at75/6/

What am I doing wrong? 我究竟做错了什么?

 var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext("2d"); var ground = 130; var Player = { x: 20, y: ground, vx: 5, vy: 5, yMax: 10, gravity: 3, jumping: false }; function jump() { Player.jumping = true; } function gravity() { if (Player.jumping == true) { if (Player.y < Player.yMax) { Player.y += Player.vy; } else { Player.y -= Player.vy; } } else { Player.y = ground; } } function createPlayer() { ctx.fillStyle = "red"; ctx.fillRect(Player.x, Player.y, 50, 50); } function createGround() { ctx.fillStyle = "blue"; ctx.fillRect(0, 180, 100, 50); } function ClearCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); } setInterval(function() { ClearCanvas(); gravity(); createGround() createPlayer(); }, 20); canvas.addEventListener("click", jump); 
 #myCanvas{ border:1px solid red; } 
 <canvas id="myCanvas" width="400" height="200">click</canvas> 

As @Nicolás Marzano says, separate your jumping and falling logic. 就像@NicolásMarzano所说的,分开你的跳跃和下降逻辑。

Alternatively (although the effect is slightly different) you might consider an actual gravity-style acceleration towards the ground, instead - the jump will look more realistic and it can be easier to programme. 另外(尽管效果略有不同),您可能会考虑对地面施加实际的重力式加速度,而是-跳跃看起来更逼真,并且编程起来更容易。

var Player = {
  x: 20,
  y: ground,
  jumpSpeed: 5,
  vx: 0,
  vy: 0,
  gravity: 0.1
};

function jump() {
  Player.vy = -Player.jumpSpeed;
}

function gravity() {
  Player.y += Player.vy;
  Player.vy += Player.gravity;
  if (Player.y >= ground) {
     Player.y = ground;
     Player.vy = 0;
  }
}

https://jsfiddle.net/sjcmrn/f1bw9nx1/10/ https://jsfiddle.net/sjcmrn/f1bw9nx1/10/

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

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