Warehouse address: github.com/haiyoucuv/W…

Introduced concept: simulate gravity

In the last section we improved the GameObject and added a public variable to get the width and height of the screen, implemented background scrolling and ground scrolling, and added far slower, near faster effects

This section will take you to implement the main character in FlppyBird

  • Simple free fall
  • Click on the screen to fly

1. The Bird

  • Increased 1.gravityRepresents the acceleration of gravity, and places the bird’s position in the center of the screen by default
class Bird extends GameObject {

	speed;  // How much distance does bird's speed move each time

	gravity;    // Gravitational acceleration

	constructor(id, gravity = 0.2, speed = 0) {
		super(id);
		this.speed = speed; / / save the speed
		this.gravity = gravity; / / save the gravity

		// Put it in the right place
		const { width, height } = this.size;
		this.top = (winSize.height - height) / 2 - 100;
		this.left = (winSize.width - width) / 2;
	}

	/ *... * /

}
Copy the code
  • 2. Rewrite Bird’s life cycleupdate

Velocity formula v = v0 + a times t squared velocity = velocity + acceleration times time squared

According to the speed formula, we can easily calculate the current frame speed and calculate the current position

class Bird extends GameObject {

	/ *... * /

	update() {
		super.update();

		// v = v0 + a * t²
		this.speed += this.gravity; // Velocity = velocity + acceleration times time ²

		this.top += this.speed;  // Update the location}}Copy the code
  • 3. Modify the Bird creation

There is no need to pass in a new parameter because the default parameter is specified

    / / create a bird
const bird = new Bird("bird");
Copy the code

Run the case and find that Bird quickly falls off the screen, never to return

  • 3. Tap the screen to leap

Modify the callback function of the click screen. After the click, change the Bird speed attribute to negative to achieve the effect of flying

// Use mousedown to listen for mouse clicks and get the position of mouse clicks
const mouseDown = (e) = > {
	bird.speed = -8;
}
document.addEventListener('mousedown', mouseDown);
Copy the code

Run the case again and click on the screen to find Bird flying up