Smooth character movement in canvas game using keyboard controls(使用键盘控制在画布游戏中流畅地移动角色)
本文介绍了使用键盘控制在画布游戏中流畅地移动角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Canvas和JavaScript创建一个侧滚无限空间为主题的游戏。我正在使用向上和向下箭头来控制一艘宇宙飞船,我想要实现某种移动放松,这样当我松开钥匙时,飞船就不会停下来。我环顾四周,没有发现任何东西,而且我自己的尝试也没有奏效。这就是我尝试过的。
Jet.prototype.checkDirection = function () {
if (this.isUpKey) {
this.drawY -= this.speed;
if (this.speed < 5) {
this.speed += 0.1;
}
}
if (this.isDownKey) {
this.drawY += this.speed;
if (this.speed < 5) {
this.speed += 0.1;
}
}
if (!this.isUpKey) {
if (!this.isDownKey) {
if (this.speed >= 0) {
this.drawY -= this.speed;
this.speed -= 1;
}
}
}
if (!this.isDownKey) {
if (!this.isUpKey) {
if (this.speed >= 0) {
this.drawY += this.speed;
this.speed -= 1;
}
}
}
推荐答案
您只想施加一些摩擦力。这很容易。您可以执行类似以下操作。
this.speed*=0.98;
值越小(0.8、0.5等),速度就越快。
我提供了一个演示,您可以在其中四处移动,并逐渐减慢速度。继续使用该值,看看它如何影响它。
Live Demo
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = canvas.height = 300;
var x = 150, //initial x
y = 150, // initial y
velY = 0,
velX = 0,
speed = 2, // max speed
friction = 0.98, // friction
keys = [];
function update() {
requestAnimationFrame(update);
// check the keys and do the movement.
if (keys[38]) {
if (velY > -speed) {
velY--;
}
}
if (keys[40]) {
if (velY < speed) {
velY++;
}
}
if (keys[39]) {
if (velX < speed) {
velX++;
}
}
if (keys[37]) {
if (velX > -speed) {
velX--;
}
}
// apply some friction to y velocity.
velY *= friction;
y += velY;
// apply some friction to x velocity.
velX *= friction;
x += velX;
// bounds checking
if (x >= 295) {
x = 295;
} else if (x <= 5) {
x = 5;
}
if (y > 295) {
y = 295;
} else if (y <= 5) {
y = 5;
}
// do the drawing
ctx.clearRect(0, 0, 300, 300);
ctx.beginPath();
ctx.arc(x, y, 5, 0, Math.PI * 2);
ctx.fill();
}
update();
// key events
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
这篇关于使用键盘控制在画布游戏中流畅地移动角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:使用键盘控制在画布游戏中流畅地移动角色
基础教程推荐
猜你喜欢
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
- HTML5 画布调整为父级 2022-01-01
- 从快速中间件中排除路由 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
