I’m working on a game and I’m trying to get the main character to move left and right while playing an animation. The animation plays and the character moves in the correct direction, when I press the arrow keys however the character teleports across the screen really fast, you can just about see the running animation play.
I can get the animation to go smoothly and even the character moving in any direction I want, its only when I try to apply the keyboard events I get this problem.
I’m still a beginner so I could be way off but I think this is happening because I put the code that updates the animation frames (setTimeout) in the same function as the code for the key inputs just can’t find a way around this.
Its not much so I’ll post all the code here. Thanks for any help.
[code]
//Image
//var sx = count;
var sy=64;
var sw=32;
var sh=32;
var dx=0;
var ypos=353;
var dw=32;
var dh=32;
xpos=50;
var count=0;
var count1=0;
var bulletxpos= xpos+27;
var bulletypos= ypos+23;
var bullets = new Image ();
var shot = new Image ();
bullets.src=“Img/bullet.png”;
shot.src=“Img/shot.png”
function draw() {
//Create Canvas
var canvas = document.getElementById(“canvas”);
var ctx = canvas.getContext(“2d”);
//Draw images on canvas
var pic= new Image ();
var bullet=new Image ();
var deku= new Image ();
var img= new Image ();
dekub= new Image ();
pic.src=“Img/Background.png”;
deku.src=“Img/deku.png”;
img.src=“Img/Spritesheet1.png”;
;
//LOAD BACKGROUND
pic.addEventListener(“load”, function () {ctx.drawImage (pic,0,0) }, false);
//LOAD MAIN CHARACTER
img.addEventListener ("load", function stand () {ctx.drawImage (img, count, sy, sw, sh, xpos, ypos, dw, dh) }, false);
//BUTTONS
window.addEventListener(“keydown”, checkkey, false);
window.addEventListener(“keydown”, checkkeypress, false);
window.addEventListener(“keyup”, checkup, false);
window.addEventListener (“keyup”, checkkeyup, false);
//RIGHT KEY PRESS
function checkkey (key) {
if (key.keyCode==39) {
xpos=xpos+3;
sy=0;
if (count ==768)
count=0
else count=count+32;
}
}
//LEFT KEY PRESS
function checkkeypress (key) {
if (key.keyCode==37) {
xpos=xpos-3;
sy=32;
if (count ==736)
count=0
else count=count+32;
}
}
//RIGHT KEY RELEASE
function checkup (key) {
if (key.keyCode==39) {
sy=64;
if (count==480)
count=0;
else count=count+32;
}
}
//LEFT KEY RELEASE
function checkkeyup (key) {
if (key.keyCode==37) {
sy=96;
if (count==480)
count=0;
else count=count+32;
}
}
//ANIMATION SPEED
setTimeout(draw, 34);
//STAND AMIMATION
if (count==480)
count=0;
else count=count+32;
}
</script>
[/code]