//operates on rectMode(CENTER)
//blocks should be higher and wider than player's movement speeds
MovingBlock player;
ArrayList<StationaryBlock> blocks=new ArrayList<StationaryBlock>();
void setup() {
size(800, 600);
player=new MovingBlock(width/2, width/2-200, 60, 80);
player.vy=0;
blocks.add(new StationaryBlock(400, 400, 120, 30));
blocks.add(new StationaryBlock(200, 300, 60, 60));
blocks.add(new StationaryBlock(400,383,60,20));
blocks.add(new StationaryBlock(600,500,60,70));
rectMode(CENTER);
player.moveSpeed=5;
player.jumpSpeed=12;
}
void draw() {
background(255);
fill(255, 100, 0);
player.move();
for (int i=0;i<blocks.size();i++) { //displays all blocks and checks if they are colliding with the player
StationaryBlock b=blocks.get(i);
player.collide(b.x, b.y, b.w, b.h);
b.display();
}
player.display();
}
void keyPressed() {
if (key==CODED && keyCode==LEFT) player.vx=-1*player.moveSpeed; //move left
if (key==CODED && keyCode==RIGHT) player.vx=player.moveSpeed; //move right
if (key==CODED && keyCode==UP && player.vy==0) { //jumps!
player.y-=player.jumpSpeed;
player.vy=-1*player.jumpSpeed;
}
}
void keyReleased() {
if (key==CODED && keyCode==LEFT && player.vx<0) player.vx=0;
if (key==CODED && keyCode==RIGHT && player.vx>0) player.vx=0;
}
class MovingBlock {
float x, y, w, h, vx, vy;
float moveSpeed;
float jumpSpeed;
MovingBlock(float x, float y, float w, float h) {
this.x=x;
this.y=y;
this.w=w;
this.h=h;
}
void move() { //moves the player
x+=vx;
y+=vy;
if (y>=height-h/2) {
y=height-h/2;
vy=0; //floor
} else if (y<height) {
vy+=0.32; //gravity
}
}
void display() { //draws the player
fill(255, 100, 0);
rect(x, y, w, h);
}
void collide(float bx, float by, float bw, float bh) { //takes info of stationary block
if (collidedWithBlock(bx, by, bw, bh)) {
float dx=abs(bx-x);
float dy=abs(by-y);
float gapx=dx-(w+bw)/2;
float gapy=dy-(h+bh)/2;
if (gapx<=gapy) {
if (vy<=0 && y>by+bh/2) { //hit bottom of block
y+=jumpSpeed/2;
vy=0;
} else if (vy>0 && y<by+bh/2) { //hit top of block
y=by-((h+bh)/2-1);
vy=0;
}
} else {
if (vx<0 && x>bx) { //hit right of block
x=bx+(w+bw)/2;
}
if (vx>0 && x<bx) { //hit left of block
x=bx-(w+bw)/2;
}
}
}
}
boolean collidedWithBlock(float bx, float by, float bw, float bh) { //returns true if the player is touching the block
float dx=abs(bx-x);
float dy=abs(by-y);
return dx<(bw+w)/2 && dy<(bh+h)/2;
}
}
class StationaryBlock {
float x, y, w, h;
StationaryBlock(float x, float y, float w, float h) {
this.x=x;
this.y=y;
this.w=w;
this.h=h;
}
void display() { //draws the block
fill(255, 0, 0);
rect(x, y, w, h);
}
}