In your game or application you may want to have collision detection. This may include:
Collision between player and enemy
Mouse over objects with mouse
Collisions between two objects
There are a couple of ways of detecting a collision with two objects.
1a. Create your own function to check the x and y position of each object using dist() which returns the distance of pixels between two x and y positions
// the distance from point 1 to point 2.
let d = int(dist(x1, y1, x2, y2));
We can then write an if statement for two eclipse shapes
var d = dist(b1.x,b1.y,b2.x,b2.y);
if ( d < (b1.r + b1.r)){
//do something
}
Rectangle Example
var rect1 = {x: 5, y: 5, width: 50, height: 50}
var rect2 = {x: 20, y: 10, width: 10, height: 10}
if (rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.y + rect1.height > rect2.y) {
// collision detected!
}
See another example with a click function:
Purple and grey have detection enabled
Part 1
Part 2
You will need to import the lib code into your index.html file
<script src="https://cdn.jsdelivr.net/gh/bmoren/p5.collide2D@0.6/p5.collide2d.js"></script>
There are many different inbuilt funtions that you can use in this library:
collidePointRect(Xpoint,Ypoint,x,y,width,height);
var hit = false;
function setup() {
createCanvas(1000,300);
}
function draw(){
noStroke();
rect(400,100,200,100);
hit = collidePointRect(mouseX,mouseY,400,100,200,100);
//see if the mouse is in the rect
if(hit){
fill('purple') //change color!
}
else{
fill('green')
}
}