好吧,我有一个图像,我可以通过按键在 Canvas 上移动(WASD。)
问题是,如果你查看动画(如果你想看的话,可以在我的网站 maddogathecanadianunicorn.batcave.net/project5.html 上查看),它移动得太快了。不是动画本身的问题,而是 Action 太快了。
有什么办法可以降低它每秒移动的速度或其他东西吗?也许这与 FPS 有关?
我的代码如下。
function initCanvas(){
var canvas = document.getElementById('my_canvas')
var ctx = canvas.getContext('2d');
//Variables
var cw = canvas.width;
var ch = canvas.height;
var x = 20;
var y = 20;
var width = 40;
var height = 40;
var srcx = 0;
var srcy = 0;
//----------------
//Char (Spritesheet soon)
//----------------
var char = new Image();
char.src = "spritesheet.png";
//
draw(); //Executes the Draw Function
//
//-------------
//WASD Controls
//-------------
document.addEventListener("keydown", move, false);
function move(event){
//---
//W
//---
if(event.keyCode == 87){ //w
//ANIMATOR
srcy = 0;
srcx+=33;
if(srcx === 66){
srcx = 0;
}
//CHAR MOVER
if(y >= 20){
y-=20;
}
/* This loops it back around.
else if(y < 20){
y = 460;
}
*/
}
//---
//A
//---
if(event.keyCode == 65){ //a
//Animator
srcy = 66;
srcx+=33;
if(srcx === 66){
srcx = 0;
}
//CHAR MOVER
if(x >= 20){
x-=20;
}
/*Loops it back around
else if(x < 20){
x = 460;
}
*/
}
//---
//S
//---
if(event.keyCode == 83){ //s
//Animator
srcy = 33;
srcx+=33;
if(srcx === 66){
srcx = 0;
}
//CHAR MOVER
if(y+height <= 490){
y+=20;
}
/*Loops Char back...
else if(y+height > 460){
y = 0;
}
*/
}
//---
//D
//---
if(event.keyCode == 68){ //d
//Animator
srcy = 100;
srcx+=33;
if(srcx === 66){
srcx = 0;
}
//Mover
if(x+width <= 490){
x+=20;
}
/*Loops Char Back
else if(x+width > 490){
x = 0;
}
*/
}
draw();
//Idea for sprite: If press right it goes right and loads a gif while going right...
//And when "keyup" or keyrelease or whatever, it stops the animation
//Or loads a neutral one facing the same direction.
}
//--------------
//Draw Function
//--------------
function draw(){
//Clears rect for animation purposes
ctx.clearRect(0, 0, cw, ch);
ctx.fillStyle = "green";
//ctx.fillRect(x, y, 20, 20);
ctx.drawImage(char, srcx, srcy, 32, 32, x, y, width, height);
}
}
//------------
//Game Loop
//------------
window.addEventListener('load', function(event){
initCanvas();
});
最佳答案
只需为 Angular 色移动的每个点添加冷却时间即可。
示例:
movement_cd_per_cell = 300; //movement speed in milliseconds
move_able = true;
//this interval will serve as a refresher for every time the character moves
setInterval(function(){ move_able = true;}, movement_cd_per_cell );
//shortened move function
function move(event){
//---
//W
//---
//add into the condition move_able to check if the character can move again.
if(event.keyCode == 87 && move_able == true){ //w
//ANIMATOR
srcy = 0;
srcx+=33;
if(srcx === 66){
srcx = 0;
}
//CHAR MOVER
if(y >= 20){
y-=20;
move_able = false; //add this line to prevent anymore movement
}
}
希望这有帮助。 :)
旁注:: 即使 Angular 色不移动,冷却时间仍然会继续,这只是减慢移动速度的一种解决方案。如果您希望冷却时间在移动时开始,则必须在移动事件上实例化冷却计时器变量以使其顺利移动。
关于javascript - HTML CANVAS 减慢运动速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28732612/