How to remove array object when mouse pressed

Hi @tefa

Thxs for sharing your classes. This is what I call “readable code”, which means it is easier to follow. Code like this is easier to debug and to maintain. Yes, you are right. From time to time it is good to rewrite your code, specially at this early stage when you are working with new concepts or you are introducing new features. I put your code above together and I got a running version.

I encourage you to see the following post: Random boxes and circles using array(s)

Just copy and paste it in a new sketch. You need to press the key up or down when the sketch is running to control the character there. Have a look at the Coin and Bomb classes and see if you can understand their connection and why they were put together that way. If you find it useful, and if you understand what is going on, you could implement it in your game. You don’t have to but more for you to see a different approach.

Kf

//Game game;
//Whale whale;
Crab crab;

float time = 0;

void setup() {
  size(640, 640);
  //game = new Game();
  crab = new Crab();
  //whale = new Whale();

  frameRate(60);
}

void draw() {
  background(30);
  noStroke();
  fill(0);
  rect(0, height/2, width, height/2);

  //game.display();
  //game.reward();

  //whale.display();
  crab.crabWalk();
  crab.display();
}

void mousePressed() {
  //game.trash();
}

class Crab {
  PImage img;
  float xE = 0;
  float yE = 0;
  int w = int(370/4);
  int h = int(215/4);
  float ellipseXSpeed = 1;
  float ellipseYSpeed = 1;

  float lastTimeChecked;
  float counter = 4000.00;

  Crab() {
    lastTimeChecked = millis();
    img = createAnImage(w, h, color(255, 0, 0), color(150, 150, 0)); //loadImage("aceituna.png");
  }

  void crabWalk() {
    xE += ellipseXSpeed;
    yE += ellipseYSpeed;

    boolean dirChange=false;
    if (xE < 0 || xE + (w/2)  > (width) - w /2 ) {
      ellipseXSpeed *= -1;
      xE %= width;
      dirChange=true;
    }
    if (yE < 0  || yE + (h/2)  > (height/2) - h / 2 ) {
      ellipseYSpeed *= -1;
      yE %= height;
      dirChange=true;
    }

    //Only perform next if the direction was not change recently. Avoids some glitches ocurring duringedge checking 
    if (!dirChange && millis()  > lastTimeChecked + counter) {     
      lastTimeChecked  = millis();     
      //xE -= ellipseXSpeed;
      ellipseXSpeed *= -1;
    }
  }

  void display() {
    imageMode(CORNER);
    tint(255, 255);
    image(img, xE, yE, w, h);
  }

  PImage createAnImage(int w, int h, color c1, color c2) {

    PImage imgx=createImage(w, h, ARGB);
    imgx.loadPixels();
    for (int i=0; i<w*h; i++) {
      imgx.pixels[i]=lerpColor(c1, c2, (i%w)/float(w));
    }
    imgx.updatePixels();

    return imgx;
  }
}

1 Like