我一直在尝试使用HTML的Canvas元素进行基本的游戏循环。在线上的许多教程都没有对渲染和canvas.ctx(上下文)的概念进行足够详细的介绍。
[我想做的事情很简单:在画布元素上渲染图像,并在按下键时更新其位置并将其渲染到新位置,使其在屏幕上移动。基本上,每个视频游戏用它的精灵做什么。
通过这些教程,我被告知ctx.drawImage(image, x, y, ...)
将为此工作。但是,最终在我的版本中发生的事情基本上是当您在Windows上赢得纸牌游戏时发生的事情。 [每次游戏循环时,它都会重复创建一个新的Sprite来重复Sprite的图像。 Sprite本身不动,似乎在原始Sprite的左/右/等位置生成了一个新Sprite。我了解每次我在游戏循环中进行迭代时都会调用ctx.drawImage(...)
。但是,当我使用ctx.clearRect(...)
时并没有发生。它确实按我预期的那样工作。我不确定为什么用ctx创建矩形却不能创建图像。
我的问题是:有没有一种方法可以简单地更新子画面的位置,而不必在每个循环中都为其创建全新的版本?
这是我的相关代码:
let lastRender = 0; // For the general loop
let image = new Image();
image.src = "/img/image.png";
let state = {
pressedKeys: {
// left, right, up, down: false
},
position: {
x: canvas.width / 2,
y: canvas.width / 2
},
speed: 20
}
let pepsi = new Sprite({
img: image,
width: 100,
height: 100
)};
function Sprite (options) {
this.img = options.img;
this.width = options.width;
this.height = options.height;
this.render = function(){
ctx.drawImage(
this.img,
state.position.x,
state.position.y
)
}
}
function updatePosition(progress) {
//pressedKeys is just an object that relates WASD to the key codes
// and their respective directions, it's ignorable
if (state.pressedKeys.left) {
state.position.x -= state.speed;
}
if (state.pressedKeys.right) {
state.position.x += state.speed;
}
if (state.pressedKeys.up) {
state.position.y -= state.speed;
}
if (state.pressedKeys.down) {
state.position.y += state.speed;
}
}
function draw() {
pepsi.render();
}
function loop(timestamp) {
let progress = timestamp - lastRender;
update(progress) // <-- Updates position, doesn't touch draw()
draw(); // <-- Runs pepsi.render(); each loop
lastRender = timestamp;
window.requestAnimationFrame(loop);
}
window.requestAnimationFrame(loop); // for the general loop
如果您对本项目的设置方式有任何疑虑(例如,对each Sprite使用state.position,那么除了解决我的问题外,我很高兴听到他们的声音。不是孤立的。我从无上下文的,非特定的在线教程中获得了大部分代码,但是我理解了其中的大部分内容,只是用于渲染。
[此外,如果您之前已经看过此类问题,并且对说“ {四年前与{Borderline正切相关帖子}的可能重复”]]持怀疑态度,那么这里有一些建议:请回答再问一次。从字面上看,它对您没有任何负面影响。
我一直在尝试使用HTML的Canvas元素进行基本的游戏循环。在线上的许多教程都没有对渲染和canvas.ctx(上下文)的概念进行足够详细的介绍。我是...
您获得的单人纸牌拖影效果是因为每一帧都画在最后一帧的顶部上。画布不会在两帧之间自动清除。