Premium Features
Let's add a camera that follows the player horizontally, revealing more of the level as they move.
Instead of panning the camera directly based on player position, we use a "camera box" — an invisible rectangle around the player:
this.cameraBox = { position: { x: this.position.x, y: this.position.y }, width: 200, height: 80 }Check if the camera box hits the screen edges:
Right edge — When camera box right side exceeds canvas width, translate everything left
Left edge — When camera box left side goes below zero, translate everything right
if (cameraBox.position.x + cameraBox.width >= canvas.width) { camera.position.x -= player.velocity.x }Before drawing your scene, translate by the camera position:
c.translate(camera.position.x, camera.position.y)The camera box gives the player some room to move before the camera starts panning, creating a smoother gameplay feel.
Comments
Want to participate?
Create a free Chris Courses account to begin
No comments yet, be the first to add one