好吧,所以我有一张图片,我正用画笔在画布上移动(WASD。)
问题是,如果你看看动画(你可以在我的网站上查看maddogathecanadianunicorn.batcave.net/project5.html,如果你想看到它),它移动得太快了。这不是动画本身,而是动作太快了。
有没有办法可以降低每秒的移动量或什么?也许它与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();
});
答案 0 :(得分:1)
只需为角色移动的每个点添加冷却时间。
示例:
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
}
}
希望这会有所帮助。 :)
图片的标题说明:: 即使角色没有移动,冷却仍然会继续,这只是缓慢减速的一种解决方案。如果你想要在移动时开始冷却,你必须在移动事件中实例化一个冷却计时器变量,以使其顺利移动。