Detecting if object is within image

usually the collision used is by a concept, see
Help for create collision between the characters ,
but also possible just to check on a color change in the direction a object should go.

example code:

PImage img;
float speed = 0.3, ang, dang=0.3, clim = 200;                    // fix set color limit
PVector dir = new PVector(1, 1, 0), pos, go= new PVector(0, 0, 0);

void setup() {
  size(500, 500);
  img = loadImage("data/body.png");
  pos = new PVector(width/2, height/2, 0);
  rectMode(CENTER);
}

void draw() {
  image(img, 0, 0);
  virus_move();
}

void virus_move() {
  go = dir.copy();
  go.mult(speed);
  go = go.add(pos);
  color c = img.get(int(go.x), int(go.y));              // get color on next position
  float cval = brightness(c);                           // use brightness
  if ( cval > clim )   dir = PVector.random2D();        // let it move somewhere else
  else                 pos = go.copy();                 // ok can use pos
  translate(pos.x, pos.y);
  ang += dang;
  rotate(ang);
  fill(200, 0, 0);
  stroke(0, 200, 0);
  rect(0, 0, 6, 6);
}

1 Like