S2
jS
Learn
Create Your Own
Split Screen
Go to Live Site
Next Page
Can you figure out how to
make the hero go faster
?
Try
some things.
<html> <head> <title>Better keyboard handling</title> </head> <body> <canvas id="myCanvas" width=300 height=300 style="background-color: olive"> </canvas> <script> var ctx = myCanvas.getContext("2d"); // Get the drawing context for the canvas var FPS = 40; // How many frames per second function MySprite (img_url) { this.x = 0; this.y = 0; this.visible= true; this.velocity_x = 0; this.velocity_y = 0; this.MyImg = new Image(); this.MyImg.src = img_url ; } var hero= new MySprite("http://s2js.com/img/etc/burger.png"); // The hero addEventListener("keydown", MyKeyDownHandler); // listen for keystrokes addEventListener("keyup", MyKeyUpHandler); // listen for keys released function Do_a_Frame () { ctx.clearRect(0, 0, myCanvas.width, myCanvas.height); // clear the background ctx.font="20px arial"; ctx.fillText("Hero x=" + hero.x + " y=" + hero.y, 0, 20); // show hero coordinates hero.Do_Frame_Things(); // hero } MySprite.prototype.Do_Frame_Things = function() { // if the x-velocity is to the left, only apply the velocity if the sprite is not off-screen to the left< if ((this.velocity_x < 0) && (this.x > 0)) this.x = this.x + this.velocity_x; // if the x-velocity is to the right, only apply the velocity if the sprite is not off-screen to the right< if ((this.velocity_x > 0) && (this.x + this.MyImg.width < myCanvas.width )) this.x = this.x + this.velocity_x; // if the y-velocity is upward, only apply the velocity if the sprite is not off-screen at the top if ((this.velocity_y < 0) && (this.y > 0)) this.y = this.y + this.velocity_y; // if the y-velocity is downward, only apply the velocity if the sprite is not off-screen at the bottom if ((this.velocity_y > 0) && (this.y + this.MyImg.height< myCanvas.height)) this.y = this.y + this.velocity_y; if (this.visible) ctx.drawImage(this.MyImg, this.x, this.y); // draw the thing } function MyKeyUpHandler (MyEvent) { if (MyEvent.keyCode == 37 || MyEvent.keyCode == 39) {hero.velocity_x= 0}; // not left or right if (MyEvent.keyCode == 38 || MyEvent.keyCode == 40) {hero.velocity_y= 0}; // not up or down } function MyKeyDownHandler (MyEvent) { if (MyEvent.keyCode == 37) {hero.velocity_x= -3}; // left if (MyEvent.keyCode == 38) {hero.velocity_y= -3}; // up if (MyEvent.keyCode == 39) {hero.velocity_x= 3}; // right if (MyEvent.keyCode == 40) {hero.velocity_y= 3}; // down MyEvent.preventDefault() } setInterval(Do_a_Frame, 1000/FPS); // set my frame renderer </script> </body> </html>