Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
ArrayList<Ball> ballList = new ArrayList<Ball>();
Ball mouseBall;
void setup()
{
  size(600, 800);
  ballList.add(new Ball(width/2, height/2, 40));
  mouseBall = new Ball(mouseX, mouseY, 20);
}
void draw()
{
  background(255);
  mouseBall.update(mouseX, mouseY);

  for (int i = 0; i<ballList.size(); i++) {
    ballList.get(i).drawBall();
    mouseBall.checkCollision(ballList.get(i)._position, ballList.get(i)._radius);
  }
    mouseBall.drawBall();
}
class Ball {
  PVector _position = new PVector();
  int _radius;
  int colour = 250;
  public Ball(int x, int y, int r) {
    _position.set(x, y, 0);
    _radius = r;
  }
  void update(int x, int y) {
    _position.set(x, y, 0);
  }

  void drawBall() {
    pushMatrix();
    fill(colour, 0, 0);
    noStroke();
    translate(_position.x, _position.y);
    ellipse(0, 0, _radius*2, _radius*2);
    popMatrix();
  }

  void checkCollision(PVector position, int radius) {
    float distance = PVector.dist(_position, position);
    if (distance <= radius +_radius) {
      println("hit");
      colour = 60;
    } else {
      colour = 255;
    }
  }
}


Point and Polygon

Sometimes it is only necessary to check if one specific points is inside a very complex shape. This complex shape can even be convex, which means that the edges of the polygon do not only point to the outside, but maybe also to the inside.

Image Added

But there is a simple solution to check, if a point is located inside or outside this complex shape. W. Randolph Franklin created this method to check, if a point is located inside an Array of points. This is an adapted version for processing.

Code Block
languagejava
firstline1
titlePNPoly
boolean pnpoly(PVector[] vertices, float testx, float testy)
{
  int i, j;
  boolean c = false;
  for (i = 0, j = vertices.length-1; i < vertices.length; j = i++) {
    if ( ((vertices[i].y>testy) != (vertices[j].y>testy)) 
      && (testx < (vertices[j].x-vertices[i].x) * (testy-vertices[i].y) / (vertices[j].y-vertices[i].y) + vertices[i].x) )
      c = !c;
  }
  return c;
}


Bitmap Collision

For complex shapes, it's possible to create a reference bitmap to indicate hit areas. This reference can be black and white images, which correlates exactly to an image or shape that will be displayed on the screen. This method works well for game maps, and in situations where you are testing a simple shape against a complex one. 

...