UNPKG

kontra

Version:

Kontra HTML5 game development library

78 lines (70 loc) 1.9 kB
<!DOCTYPE html> <html> <head> <title>Controlling A Sprite</title> <script src="../../kontra.js"></script> </head> <body> <canvas id="game" width="600" height="400" style="background: #333331"></canvas> <script id="code"> // initialize the game and setup the canvas let { canvas, context } = kontra.init(); kontra.initKeys(); // create a basic sprite with a velocity window.sprite = kontra.Sprite({ x: 290, y: 180, dx: 3, dy: 3, width: 20, height: 40, color: 'red', // pass a custom update function to the sprite update: function() { // move the sprite with the keyboard if (kontra.keyPressed('up')) { this.y -= this.dy; } else if (kontra.keyPressed('down')) { this.y += this.dy; } if (kontra.keyPressed('left')) { this.x -= this.dx; } else if (kontra.keyPressed('right')) { this.x += this.dx; } // reset the sprites position when it reaches the edge of the game if (this.x > canvas.width) { this.x = -this.width; } else if (this.x < -this.width) { this.x = canvas.width; } if (this.y > canvas.height) { this.y = -this.height; } else if (this.y < -this.height) { this.y = canvas.height; } } }); // prevent default key behavior kontra.bindKeys(['up', 'down', 'left', 'right'], function(e) { e.preventDefault(); }); // create the game loop to update and render the sprite window.loop = kontra.GameLoop({ update: function() { sprite.update(); }, render: function() { sprite.render(); } }); // start the loop loop.start(); </script> <script src="../prism/codeOutput.js"></script> </body> </html>