xxxxxxxxxx
66
// This is a small demo of how the physics works in
// Flappy Bird. Feel free to use these ideas in your
// own game. Adjust the work so that it is your own,
// and remove the explanatory comments if you do.
class Bird {
constructor(x, diameter) {
this.x = x
this.y = 0
this.diameter = diameter
this.speed = 0
}
draw() {
fill('yellow')
circle(this.x, this.y, this.diameter)
// The check makes sure the bird doesn't fall
// through the ground. Incrementing the bird's
// y position and its speed in the y-direction
// is something we learned before.
if (this.y < height) {
this.y += this.speed
this.speed += gravity
}
}
}
const gravity = 0.2
let bird
function setup() {
createCanvas(400, 400)
// Remember to create the bird after you call
// createCanvas so you can use the p5.js width
// and height variables, if needed
bird = new Bird(width / 4, 30)
}
function draw() {
background('cyan')
bird.draw()
}
function keyPressed() {
if (keyCode === 32) {
// This is it folks: the physics of Flappy Bird
// is just one line of code! When the space bar
// is pressed, just set the speed to a negative
// value! This will make it go up! The regular
// gravity computation in draw() will slow the
// ascent and make it start going down eventually.
bird.speed = -5
// Okay there is a second line: make sure the bird
// doesn't get stuck at the bottom of the canvas
// so this kind of moves it up a bit when the
// key is pressed so that it can ascend.
bird.y = min(bird.y, height - 1)
}
// Remember to always add this for p5.js keyPressed:
return false
}