Collision detection with walls and objects

Respect! Impressive!

I re-wrote it, so it’s fully running

There were a few minor typos.

Chrisir



ArrayList<sceneObj> objects = new ArrayList<sceneObj>();
Player player;

void setup() {
  size(400, 400);

  player = new Player(random(400), random(400));
  for (int i=0; i<10; i++) {
    sceneObj object = new sceneObj(random(400), random(400)); 
    objects.add(object);
  }
  background(111);
}

void draw() {
  background(111); 
  player.draw();
  player.update();

  for (int i=0; i<10; i++) {
    sceneObj o = objects.get(i);

    o.draw();

    if (o.collide())
      o.col = color(0);
    else o.col = color(255);
  }
}

// ============================================================

class Player {
  float x, y;
  boolean collide;
  color col = color(255);

  Player(float x, float y) {
    this.x = x;
    this.y = y;
  }

  void draw() {
    fill(255, 0, 0);
    rect(x, y, 20, 40);
  }

  void update() {
    if (keyPressed&&keyCode==LEFT) {
      x-=5;
    }
    if (keyPressed&&keyCode==RIGHT) {
      x+=5;
    }

    if (keyPressed&&keyCode==UP) {
      y-=5;
    }
    if (keyPressed&&keyCode==DOWN) {
      y+=5;
    }
  }
}

// ============================================================

class sceneObj {

  float x, y;
  boolean collide;
  color col = color(255);

  sceneObj (float x, float y) {
    this.x = x;
    this.y = y;
  }

  void draw() {
    fill(col);
    rect(x, y, 20, 20);
  }

  boolean collide() {
    return
      player.x>x&&
      player.x<x+20&&
      player.y>y&&
      player.y<y+20;
  }
}