Premium Features
Every game needs a protagonist. In this lesson, we'll create a player object, implement an animation loop, add basic collision detection, and refactor everything into a clean class structure.
Start with the simplest possible representation—a colored rectangle:
c.fillStyle = 'red' c.fillRect(100, 100, 100, 100)This draws a 100x100 pixel red square at position (100, 100).
Static images don't make a game. We need continuous rendering:
function animate() { window.requestAnimationFrame(animate) // Drawing code goes here } animate()
requestAnimationFramecalls your function before each screen repaint, typically 60 times per second. This creates smooth animation.
To create movement, we update the Y position each frame:
let y = 100 function animate() { window.requestAnimationFrame(animate) c.fillStyle = 'white' c.fillRect(0, 0, canvas.width, canvas.height) c.fillStyle = 'red' c.fillRect(100, y, 100, 100) y++ }We clear the canvas each frame with a white rectangle, then redraw the player at its new position.
Without boundaries, our player falls forever. Add a simple collision check:
const bottom = y + 100 // player height if (bottom < canvas.height) { y++ }As code grows, organization becomes critical. Encapsulate the player in a class:
class Player { constructor() { this.position = { x: 100, y: 100 } this.width = 100 this.height = 100 } draw() { c.fillStyle = 'red' c.fillRect( this.position.x, this.position.y, this.width, this.height ) } update() { // Movement and collision logic } }Move this class to a separate js/classes/Player.js file. Your animation loop becomes beautifully simple:
const player = new Player() function animate() { window.requestAnimationFrame(animate) player.draw() player.update() } Classes make your code readable and maintainable. When you return to this project later, player.draw() and player.update() immediately communicate intent.
Comments
Want to participate?
Create a free Chris Courses account to begin
No comments yet, be the first to add one