Premium Features
Now let's create our player and implement realistic gravity so they fall towards the ground.
Instead of drawing rectangles procedurally, we'll use object-oriented programming. Create a Player class with position and velocity properties:
class Player {
constructor({ position }) {
this.position = position
this.velocity = { x: 0, y: 1 }
this.height = 100
}
}
This approach makes it easy to create multiple players and keeps our code organized.
To animate our player, we need a loop that runs continuously. Use requestAnimationFrame to create a recursive function:
function animate() {
requestAnimationFrame(animate)
// Clear canvas and draw player each frame
}
animate()
Always clear the canvas at the start of each frame to avoid the "drip" effect from previous renders.
Gravity isn't just falling at a constant speed — objects accelerate as they fall. Add a gravity constant that increases velocity over time:
const gravity = 0.5
// In update method:
this.velocity.y += gravity
this.position.y += this.velocity.y
To prevent the player from falling forever, check if the bottom of the player exceeds the canvas height:
if (this.position.y + this.height + this.velocity.y < canvas.height) {
this.velocity.y += gravity
} else {
this.velocity.y = 0
}
Now your player falls with realistic acceleration and stops at the ground.
Comments
Want to participate?
Create a free Chris Courses account to begin
No comments yet, be the first to add one