Atlassian uses cookies to improve your browsing experience, perform analytics and research, and conduct advertising. Accept all cookies to indicate that you agree to our use of cookies on your device. Atlassian cookies and tracking notice, (opens new window)
Confluence
For you

Programming
Results will update as you type.
  • Tiling and Repetition
  • Reactors
  • Programming Basics: Parametric and Generative Graphic Design 2016
  • Archive
  • High Scores
  • Artificial Neural Network
  • Alternatives to the Processing IDE
  • p5.js Programming
  • Programming in Processing (java)
    • Starting with Processing (en)
    • Variables (en)
    • Classes and Objects (en)
    • Events und Functions (en)
    • Writing our own Functions (en)
    • Random Numbers (en)
    • Conditionals (en)
    • Loops (en)
    • Nested Loops (en)
    • Coordinates (en)
    • Arrays and Lists (en)
    • SVG + Images (en)
    • Motion and Temporality
    • Gesture Interactions
    • Using bitmaps as modifiers
    • Vectors
    • Animation
    • Animation 2
    • Simple Collision Detection
    • Sound
    • Typography

/
Simple Collision Detection

Simple Collision Detection

Nov 12, 2020

Analytics

Loading data...

Rectangular Collision

This simple example demonstrates collisions detection between two rectangular objects. Note that this method will only work when both rectangles are axis-aligned, and only with rectangles!

However, it's possible to use this approach with invisible bounding boxes around more complex shapes. In many cases, as in old arcade games, the user may not even notice the collisions are based purely on rectangles.

int rctl1X; // rectangle One x position
int rctl1Y; // rectangle One y position
int rctl1W = 40; // rectangle One Width
int rctl1H = 70; // rectangle One Height
//
int rctl2X; // rectangle One x position
int rctl2Y; // rectangle One y position
int rctl2W = 100; // rectangle 2 Width
int rctl2H = 100; // rectangle 2 Height

void setup() {
  size(800, 600);
  noStroke();
  rectMode(CENTER);
  rctl2X = width/2;
  rctl2Y = height/2;
}

void draw() {
  background(255);
  rctl1X = mouseX; 
  rctl1Y = mouseY; 
  boolean collision = checkCollision(rctl1X, rctl1Y, rctl1W, rctl1H, rctl2X, rctl2Y, rctl2W, rctl2H);
  if (collision) {
    fill(70, 0, 0);
  } else {
    fill(255, 0, 0);
  }
  rect(rctl1X, rctl1Y, rctl1W, rctl1H);
  rect(rctl2X, rctl2Y, rctl2W, rctl2H);
}

// this method uses the center of the rectangles
boolean checkCollision(int r1x, int r1y, int r1w, int r1h, int r2x, int r2y, int r2w, int r2h) {
  // store the locations of each rectangles outer borders 
  int top1 = r1y-r1h/2;
  int bottom1 = r1y+r1h/2;
  int right1 = r1x+r1w/2;
  int left1 = r1x-r1w/2;
  int top2 = r2y-r2h/2;
  int bottom2 = r2y+r2h/2;
  int right2 = r2x+r2w/2;
  int left2 = r2x-r2w/2;

  if (top1>bottom2 || bottom1<top2 || right1<left2 || left1>right2) {
    return false;
  } else {
    return true;
  }
}


Rectangular Collision

This method uses the top left original of the rectangle and width and height to calculate the collision.

boolean checkRectangle(
  float r1x, float r1y, float r1w, float r1h, 
  float r2x, float r2y, float r2w, float r2h) {

  return (r1x < r2x + r2w &&
    r1x + r1w > r2x &&
    r1y < r2y + r2h &&
    r1y + r1h > r2y);
}

Circular Collision

The following example demonstrates a simple method for checking collisions between round objects. As in the above example, it can be used to create invisible bounding boxes for more complex shapes. 

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.

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.

PNPoly
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. 

Out background image:

Our collision reference: 

Download Source Code

In the example, we just test one pixel directly under the mouse. This could be improved by testing at multiple points on the edge of the object we are testing. 




, multiple selections available,
Related content
Programming
Programming
Luke Franzke
p5.js Animation Exercise 1
p5.js Animation Exercise 1
Luke Franzke
Bits & Atoms IV 2021
Bits & Atoms IV 2021
Florian Bruggisser (Unlicensed)
p5.js Simple Reactor
p5.js Simple Reactor
Luke Franzke
Lesson 2.4 - Exercises
Lesson 2.4 - Exercises
Luke Franzke
Modifying distribution along width and height
Modifying distribution along width and height
Luke Franzke
{"serverDuration": 17, "requestCorrelationId": "a02469faeddc4a8396af0c00f32c8716"}