# Detecting if object is within image

**URL:** <https://discourse.processing.org/t/detecting-if-object-is-within-image/9054>\
**Category:** Coding Questions\
**Created:** [March 7, 2019, 1:13am UTC](https://discourse.processing.org/t/detecting-if-object-is-within-image/9054 "2019-03-07T01:13:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![cdallan](https://avatars.discourse-cdn.com/v4/letter/c/b9e5f3/32.png) [@cdallan](https://discourse.processing.org/u/cdallan)\
**Post date:** [March 7, 2019, 1:13am UTC](https://discourse.processing.org/t/detecting-if-object-is-within-image/9054/1 "2019-03-07T01:13:22Z")

</div>

Greetings all,  
I’m a newcomer to processing and have had fun creating various designs in the program. In an attempt to tackle something more complex, I’m currently creating a game where a mouse-controlled “parasite” object moves through a human body eating nutrients scattered throughout,  
but I’m stumped on how to constrain the object’s movement to only occur within the “human body” image.  
 ![sc2](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/6/6fe5f22d098e8fefa2ad710cb53fd470c596c957.png)  
Preferably it would bounce off the inside of the image’s edges as if it was trapped inside the body.  
Thanks so much in advance!!

---

<div class="post-metadata">

**Author:** ![kll](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kll/32/964_2.png) [@kll](https://discourse.processing.org/u/kll)\
**Post date:** [March 7, 2019, 3:01pm UTC](https://discourse.processing.org/t/detecting-if-object-is-within-image/9054/2 "2019-03-07T15:01:41Z")

</div>

usually the collision used is by a concept, see  
[Help for create collision between the characters](https://discourse.processing.org/t/help-for-create-collision-between-the-characters/8791/2) ,  
but also possible just to check on a color change in the direction a object should go.

 ![2019-03-07_21-54-23_snap](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/1/11ef7ec78d002fdde2f7cb243063828d4f218d5e.png)

example code:

```auto
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);
}

```
