Interesting approach to check for black / white pixels, but probably not the most efficient.
1st, you should make a global variable PImage marketplan
or something, where you load marketplan.png
once in void setup()
.
2nd, (and this only works if it is a .png image, so a pixel is either perfectly white or perfectly black), you can check if a there is an obstacle at any given position (x, y) with the following code:
boolean obstacleAt(int x, int y) {
return marketplan.pixels[y*marketplan.width+x] == color(0);
}
In Processing, each PImage
object has a one-dimensional color arry called pixels[]
. It’s simply a list of all pixel colors, starting from the top left, going left to right, top to bottm (just like you would read the letters in a book). The way you get any color at (x, y) of any PImage image
is to index this array with image.pixels[y+image.width+x]
. This does the same as image.get(x,y)
, though it is even faster. Next, we check if this color is black, which in Processing we write as color(0)
. If the pixel is black, then this statement is true, this method returns true. If the pixel is white, this statement is false, so false is returned.
Or at least, that would be the primitive approach. The image might contain pixels that aren’t perfectly black, but should still be considered an obstacle. This is why the method should actually look like this:
boolean obstacleAt(int x, int y) {
color c = marketplan.pixels[y*marketplan.width+x];
return red(c)+green(c)+blue(c) < 3*255/2;
}
That way, any pixel that is lighter than a 50% midtone grey will be considered free, and any pixel darker than that will be considered an obstacle.
Since your lines seem to be only a few pixels wide, make sure that the agents’ speed is only at around 2-3, otherwise they might clip trough the wall (by being on one side of the wall on one frame and on the other side on the next frame).
Your approach for preventing the agents from exiting the boundaries of the window is good, but you missed one small detail. You actually need to write it like this, or else they will get stuck at the boundaries once they hit them, with no way to escape.
if (position.x < 0) {
position.x = 0;
velocity.x *= -1;
}
if (position.y < 0) {
position.y = 0;
velocity.y *= -1;
}
if (position.x > width) {
position.x = width;
velocity.x *= -1;
}
if (position.y > height) {
position.y = height;
velocity.y *= -1;
}
Note that with all of this, all you can do so far is to check for an obstacle at a certain point (x, y), the actually collision hasn’t been implemented yet.
This explanation ended up quite a bit longer than I expected, I hope I could help you.
Best, Simon