Hitbox detection?

here is an example… without the marker

I am not too happy with it

PVector player=new PVector(800, 400);
boolean jump=false;

String mapPattern =
  "111110111111111111111101111111111111111111111111111111111111111111111111111111111111111111111111111";
ArrayList<Cell>map=new ArrayList();

// ----------------------------------------------------------------------------------

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

  int i=0;
  for (char c : mapPattern.toCharArray()) {
    if (c=='1')
      map.add(new Cell(i*27, 500, true)) ;
    else map.add(new Cell(i*27, 500, false )) ;

    i++;
  }//for
  //
}//func

void draw() {
  background (0, 0, 211);

  //display player
  fill(255, 0, 0);
  stroke(0);
  ellipse(player.x, player.y, 10, 20);

  //display map
  for (Cell c : map) {
    c.display();
  }

  managePlayer();

  keysPlayer();
}//func

// -------------------------------------------------------------------------------

void managePlayer() {
  // fall/lift
  for (Cell c : map) {
    // are we inside the cell (in x)
    if (player.x-5 >= c.cell.x &&
      player.x+5   <  c.cell.x+c.w ) {
      // hit x
      if (player.y+10 < c.cell.y || c.air)
        player.y++; // fall
      else jump=false; // stop jump

      // we can lift the player when it's too low
      if (!c.air) {
        if (player.y+10 > c.cell.y) {
          player.y--;
        }
      }
    }//if
  }//for
}

void keysPlayer() {
  // player keys
  if (!keyPressed)
    return;

  if (keyCode==LEFT)
    player.x-=2;
  else if (keyCode==RIGHT)
    player.x+=2;
  else if (key==' ') {
    if (!jump)
      player.y-=32; // jump
    jump=true;
  }
}

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

class Cell {

  PVector cell=new PVector(800, 400);
  float w=27, h=27;
  boolean air=true;

  // constr
  Cell(float x, float y,
    boolean full ) {
    cell=new PVector(x, y);
    if (full)
      air=false;
  }//constr

  void display() {
    if (air) {
      noFill();
      noStroke();
    } else {
      fill(0, 255, 0);
      stroke(0);
    }

    rect(cell.x, cell.y,
      w, h);
  }//method
  //
}//class
//

1 Like