gpt4 book ai didi

Javascript Canvas 动画 Sprite 行走

转载 作者:行者123 更新时间:2023-12-03 01:26:59 26 4
gpt4 key购买 nike

我正在尝试让 Sprite 在 Canvas 上走过背景图像。理想情况下,我会在一张 Canvas 上完成这一切,但使用两张 Canvas 似乎更高效、更容易。

到目前为止我所拥有的:

Fiddle 1

Fiddle 2

来自 fiddle 1 的代码,处理最简单的动画形式:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var spritePosition = 0;
var spriteWidth = 50;
var spriteHeight = 225;
var spriteCount = 17;
var spritePlayCount = 0;
var maxSpritePlays = 3;

var sheet = new Image();
sheet.onload = function () {
animate();
}
sheet.src = "https://s33.postimg.cc/dapcxzmvj/sprite_walk.png";

var fps = 15;



function animate() {
setTimeout(function () {

if (spritePlayCount < maxSpritePlays) {
requestAnimationFrame(animate);
}

// Drawing code goes here
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(sheet,
spritePosition * spriteWidth, 0, spriteWidth, spriteHeight,
0, 0, spriteWidth, spriteHeight);

spritePosition++;
if (spritePosition > spriteCount - 1) {
spritePosition = 0;
spritePlayCount++;
}

}, 1000 / fps);
}

我希望能够让它正确行走,并了解它是如何工作的。我看到两者都使用了 sprite.widthsprite.height 的内容,我认为它们是 width/columns高度/行,但这些似乎无法正常工作。

最佳答案

你的坐标全错了。您的 spriteWidth 和 spriteHeight 值与 spritesheet 的所有值都不匹配。

此外,您的逻辑仅更新 x 轴,而您的 Sprite 表设置在多行上。
您需要更新此逻辑,以便更新 x 和 y 源位置。

最后,不要像这样混合使用 setTimeout 和 requestAnimationFrame。他们永远不会相处得很好。要实现 15FPS,您可以非常轻松地运行 requestAnimationFrame 循环,该循环将以 60FPS 触发,并且只需每四帧绘制一次 (60FPS/4 => 15FPS)。

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var xIndex = 0;
var yIndex = 0;
var cols = 5;
var rows = 4;
var spriteWidth = 265;
var spriteHeight = 200;

var sheet = new Image();
sheet.onload = function() {
animate();
}
sheet.src = "/image/eL5yV.png";
var frame = 0;

function animate() {
requestAnimationFrame(animate);
// 60FPS / 4 => 15FPS
if ((++frame) % 4 > 0) return;

ctx.clearRect(0, 0, canvas.width, canvas.height);
// update the current column
xIndex = (xIndex + 1) % cols;
// update the current row if x is 0
yIndex = xIndex === 0 ? (yIndex + 1) % rows : yIndex;
// three cells are empty on the last row...
if (yIndex === (rows - 1) && xIndex === 2)
xIndex = yIndex = 0;
// update both sourceX and sourceY
ctx.drawImage(sheet,
xIndex * spriteWidth, yIndex * spriteHeight, spriteWidth, spriteHeight,
0, 0, spriteWidth, spriteHeight);
}
<canvas id="canvas" width=350 height=350></canvas>

关于Javascript Canvas 动画 Sprite 行走,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51488397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com