如何用JavaScript实现Canvas小球按下向上方向键触发跳跃功能
实现方案
具体修改逻辑
- 新增向上方向键的监听事件,仅在小球落地时允许触发跳跃,避免空中连跳
- 给小球增加基础重力逻辑,模拟自然下落效果
- 补充落地检测,避免小球掉到画布外
- 完善
update1方法的运动更新逻辑
var canvas = document.querySelector('canvas'); var c = canvas.getContext('2d'); canvas.width = innerWidth ; canvas.height = innerHeight ; // 监听向上方向键按下动作 document.addEventListener('keydown', function(e) { if(e.key === 'ArrowUp' && ball1.y === canvas.height - ball1.radius) { ball1.dy = -15; // 数值负得越多跳跃高度越高,可自行调整 } }) function Ball(x, y, dy, radius, color) { this.x = x; // 水平位置x this.y = y; // 垂直位置y this.dy = dy // y轴方向运动速度 this.radius = radius; this.color = color; this.gravity = 0.5; // 重力值,数值越大下落速度越快 this.update1 = function() { // 更新运动状态 this.dy += this.gravity; this.y += this.dy; // 落地检测 if(this.y + this.radius >= canvas.height) { this.y = canvas.height - this.radius; this.dy = 0; } this.draw(); } this.draw = function() { c.beginPath(); c.arc(this.x, this.y, this.radius, 0, Math.PI * 2); c.fillStyle = this.color; c.fill(); c.closePath(); }; } let ball1 function init() { ball1 = new Ball(canvas.width / 2 , canvas.height - 50 , 0 , 50 , 'blue') } function animate() { requestAnimationFrame(animate); c.clearRect(0, 0, canvas.width, canvas.height); ball1.update1() } init(); animate();
内容的提问来源于stack exchange,提问作者pete
相关产品推荐
相关产品推荐

