Premium Features

Download Video

Create a player

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.

Drawing a Simple Player

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).

The Animation Loop

Static images don't make a game. We need continuous rendering:

function animate() {   window.requestAnimationFrame(animate)   // Drawing code goes here }  animate()

requestAnimationFrame calls your function before each screen repaint, typically 60 times per second. This creates smooth animation.

Making the Player Fall

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.

Stopping at the Bottom

Without boundaries, our player falls forever. Add a simple collision check:

const bottom = y + 100 // player height  if (bottom < canvas.height) {   y++ }

Refactoring into a Class

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() } 

Why This Matters

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

Login

No comments yet, be the first to add one

Providing the lift to launch your development career

© 2026 Chris Courses. All rights reserved.