Premium Features
Change levels
Entering a door should take the player to a new level. In this lesson, we'll implement level transitions with screen fades and complete the multiroom experience.
Animation Completion Callbacks
Add an onComplete property to animations that triggers when they finish:
enterDoor: { imageSrc: './img/king/enterDoor.png', frameRate: 8, frameBuffer: 6, loop: false, onComplete: () => { console.log('Enter door animation complete') gsap.to(overlay, { opacity: 1, onComplete: () => { level++ loadLevel(level) } }) } }Screen Fade with GSAP
Use GSAP to smoothly fade a black overlay over the screen:
// In animate(), draw overlay last c.fillStyle = `rgba(0, 0, 0, ${overlay.opacity})` c.fillRect(0, 0, canvas.width, canvas.height)GSAP (GreenSock) handles smooth animations with easing. It's widely used in game development for UI transitions.
Loading New Levels
Create a function that reinitializes game objects for each level:
function loadLevel(levelNumber) { // Load level-specific collision data collisionBlocks = collisionsLevelData[levelNumber].parse2D() .createObjectsFrom2D() // Reposition player player.position = levels[levelNumber].playerPosition // Load new doors doors = levels[levelNumber].doors // Fade overlay back out gsap.to(overlay, { opacity: 0 }) }Structuring Level Data
Organize level configurations for easy expansion:
const levels = { 1: { collisions: collisionsLevel1, background: './img/backgroundLevel1.png', playerPosition: { x: 100, y: 100 }, doors: [/* door sprites */] }, 2: { collisions: collisionsLevel2, background: './img/backgroundLevel2.png', playerPosition: { x: 50, y: 300 }, doors: [/* door sprites */] } }Why This Matters
Level transitions transform a single-screen demo into a complete game. This same pattern scales to dozens of levels—just add more data to your level configuration.
Comments
Want to participate?
Create a free Chris Courses account to begin
I would love to see how you would implement the player attack animation, I have tried to implement it but can't seem to get it just right. You used some techniques that were new to me in this tutorial so I have found myself stuck on getting the animation to fire smooth and naturally.