xxxxxxxxxx
Physics physics;
float ground;
PVector flyPos;
int score = 0;
int goal = 10;
int time = 20;
void setup() {
size(500, 500);
physics = new Physics(width / 2, height / 2, 2, .95);
ground = height - 50;
flyPos = randomPos();
}
void draw() {
background(0, 30, 21);
float secondsPassed = millis() / 1000;
float timeLeft = time - secondsPassed;
strokeWeight(5);
stroke(255);
noFill();
arc(100, 50, 125, 75, 0, timeLeft / time * 2 * PI);
strokeWeight(1);
if (secondsPassed > time) {
background(0);
fill(255);
textAlign(CENTER, CENTER);
if (score < goal) {
textSize(75);
text("GAME OVER", width / 2, height / 2);
} else {
fill(255, 200, 0);
textSize(75);
text("GAME WON", width / 2, height / 2);
}
textSize(50);
text("Your score was " + score, width / 2, height / 2 + 100);
noLoop();
return;
}
textSize(48);
textAlign(CENTER, CENTER);
fill(0, 255, 0);
text("?", physics.playerPos.x, physics.playerPos.y);
groundCollisionResponse(groundCollisionDetection());
if (!isOnGround())
physics.gravity();
physics.update();
if (physics.playerPos.x > width) {
physics.playerPos.x = 0;
}
if (physics.playerPos.x < 0) {
physics.playerPos.x = width;
}
if (physics.playerPos.y > height) {
physics.playerPos.y = 0;
}
if (physics.playerPos.y < 0) {
physics.playerPos.y = height;
}
text("?", flyPos.x, flyPos.y);
if (PVector.dist(physics.playerPos, flyPos) < 50) {
eatFly();
}
textSize(20);
fill(255);
if (score > goal)
fill(255, 200, 0);
text("Score: " + score + "/" + goal, 100, 50);
}
void keyPressed() {
if ((key == ' ' || key == 'w') && abs(physics.playerPos.y - ground) < 10) {
physics.addForce(0, -30);
}
if (key == 'a') {
physics.addForce(-10, 0);
}
if (key == 'd') {
physics.addForce(10, 0);
}
}
boolean groundCollisionDetection() {
if (isOnGround() && physics.playerVel.y > 0) {
return true;
}
return false;
}
void groundCollisionResponse(boolean _collisionDetected) {
if (_collisionDetected)
physics.bounce();
}
boolean isOnGround() {
return physics.playerPos.y > ground;
}
PVector randomPos() {
return new PVector(random(width), random(ground));
}
void eatFly() {
flyPos = randomPos();
score++;
}
class Physics {
PVector playerPos;
PVector playerVel;
float weight, friction;
Physics(float _xPos, _yPos, float _weight, float _friction) {
playerPos = new PVector(_xPos, _yPos);
playerVel = new PVector(0, 0);
weight = _weight;
friction = _friction;
}
void update() {
if (isOnGround())
playerVel.x *= friction;
playerPos.add(playerVel);
}
void gravity() {
addForce(0, .8);
}
void bounce() {
playerVel.y = -1 * abs(playerVel.y) / weight;
update();
}
void addForce(float x, y) {
playerVel.add(new PVector(x, y));
}
}