My projects library #4! Gallery Megathread

#54 2D simple collisions demo 1

This is a simple demo for a 2D collision detection with rectangles. The only square that can move is the player. If you find any bugs, do tell!

Code
int px = 10, py = 10, a = 20;
int cx = 0, cy = 0, speed = 1;
obstacle o = new obstacle(275, 275, 50, 50);
void setup() {
  size(600, 600);
}
void draw() {
  background(0);
  movePlayer();
  fill(255);
  square(px, py, a);
  o.display();
}
void movePlayer() {
  for (int i = 0; i < speed; i++) {
    int nx = px+cx, ny = py+cy;
    if(collision(nx,py,a,a, o.x,o.y,o.s,o.s2) == false) px = nx;
    if(collision(px,ny,a,a, o.x,o.y,o.s,o.s2) == false) py = ny;
  }
}
void keyPressed() {
  char ky = (key+"").toLowerCase().charAt(0);
  if (ky == 'a') cx = -1;
  if (ky == 'd') cx = 1;
  if (ky == 'w') cy = -1;
  if (ky == 's') cy = 1;
}
void keyReleased() {
  char ky = (key+"").toLowerCase().charAt(0);
  if (ky == 'a' && cx == -1) cx = 0;
  if (ky == 'd' && cx == 1) cx = 0;
  if (ky == 'w' && cy == -1) cy = 0;
  if (ky == 's' && cy == 1) cy = 0;
}
boolean collision(int x1, int y1, int s1, int s12, int x2, int y2, int s2, int s22) {
  if (x1>x2-s1&&y1>y2-s12&& x1<x2+s2 && y1<y2+s22) return true; //x2-s1, y2-s12, x2+s2, y2+s22
  return false;
}
class obstacle {
  int x, y, s, s2;
  obstacle(int x_, int y_, int s_, int s2_) {
    x = x_;
    y = y_;
    s = s_;
    s2 = s2_;
  }
  void display() {
    fill(0, 0, 255);
    rect(x, y, s, s2);
  }
}