[英]JavaScript Canvas sprite animation speed
我的畫布動畫有問題。 我正在使用本教程 。 這很簡單,但是現在我想以60 fps的速度制作動畫。 我嘗試了setInterval(Update, 1000/60)
,它當然可以工作,但是現在精靈有問題。 它的動畫太快了。 有什么方法可以使60fps並減慢角色精靈動畫的速度(看起來更自然)?
抱歉,我沒有實時的示例,但是要創建一個沒有ftp的sprite會有點困難。
編碼:
var canvas;
var ctx;
var dx = 10;
var x = 30;
var y = 0;
var WIDTH = 1000;
var HEIGHT = 340;
var tile1 = new Image ();
var posicao = 0;
var NUM_POSICOES = 3;
function KeyDown(e){
switch (e.keyCode) {
case 39:
if (x + dx < WIDTH){
x += dx;
posicao++;
if(posicao == NUM_POSICOES)
posicao = 1;
}
break;
case 37:
if (x + dx < WIDTH){
x -= dx;
posicao++;
if(posicao == NUM_POSICOES)
posicao = 1;
}
}
}
function KeyUp(e){
posicao = 0;
}
function Draw() {
tile1.src = posicao+".png";
ctx.drawImage(tile1, x, y);
}
function LimparTela() {
ctx.fillStyle = "rgb(233,233,233)";
ctx.beginPath();
ctx.rect(0, 0, WIDTH, HEIGHT);
ctx.closePath();
ctx.fill();
}
function Update() {
LimparTela();
Draw();
}
function Start() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
return setInterval(Update, 1000/60);
}
window.addEventListener('keydown', KeyDown);
window.addEventListener('keyup', KeyUp);
Start();
只是一個想法,一個簡單的修補程序,您可以嘗試在Spritesheet中添加額外的幀? 這也將改善您的動畫效果,而不必擔心會破壞其他東西:)
您可以“限制” Update()以減少執行頻率。
var counter=5;
function Update() {
if(--counter>0){ return; };
LimparTela();
Draw();
counter=5;
}
如果用戶按下一個鍵,則可以通過將計數器設置為0來強制動畫。
function KeyDown(e){
switch (e.keyCode) {
case 39:
if (x + dx < WIDTH){
x += dx;
posicao++;
if(posicao == NUM_POSICOES)
posicao = 1;
}
// zero the counter to force the animation now
counter=0;
break;
case 37:
if (x + dx < WIDTH){
x -= dx;
posicao++;
if(posicao == NUM_POSICOES)
posicao = 1;
}
// zero the counter to force the animation now
counter=0;
}
}
每當移動精靈時,都應將移動的像素數除以每秒的幀數。 例如,如果要以60fps的速度每秒移動dx
像素,請定義var fps = 60;
作為全局變量並執行x += dx/fps;
當你移動他時。 以前的幀速率是多少? 30fps或什么? 無論是什么,如果您希望它以60fps的速度與以前一樣,請通過將以前的dx
乘以fps,使dx
等於每秒移動的像素數。 因此,如果它以30fps的速度每幀移動10px,則使var dx = 300;
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.