UNPKG

kontra

Version:

Kontra HTML5 game development library

66 lines (59 loc) 1.65 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; } } }); // prevent default key behavior kontra.bindKeys(['up', 'down', 'left', 'right'], function(e) { e.preventDefault(); }); // clamp sprites movement to the game between x1, y1, and x2, y2 sprite.position.clamp(0, 0, canvas.width - sprite.width, canvas.height - sprite.height); // 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>