I have set up a simple p5.js program where two circles are drawn on the screen, the deposition of one of which is determined by the cursor, and when they come in contact, the immobile one changes color. The code is the following:
let r1 = 70;
let r2 = 90;
let x2;
let y2;
function setup() {
createCanvas(400, 400);
x2 = width/2;
y2 = height/2;
}
function draw() {
background(220);
circle(mouseX, mouseY, r1);
let distance = sqrt((x2 - mouseX)*(x2 - mouseX) + (y2 - mouseY)*(y2 - mouseY));
push();
if (distance <= r1 + r2) {
fill(56, 45, 78);
}
circle(x2, y2, r2);
pop();
}
The way I'm doing the collision detection is by comparing the distance between the two circles to the sum of their radii. If the former is inferior or equal to the latter, it should normally register as a collision and change the immobile circle's color. However, that is not what happens:
As you can see, the collision detection fires up way before there is any contact, and I have no idea why.
The 3rd argument of the circle
function is the diameter, not the radius. Multiply the radius by 2.
Use the dist
function to compute the distance between 2 points.
let r1 = 70;
let r2 = 90;
let x2;
let y2;
function setup() {
createCanvas(400, 400);
x2 = width/2;
y2 = height/2;
}
function draw() {
let distance = dist(mouseX, mouseY, x2, y2);
background(220);
circle(mouseX, mouseY, r1*2);
push();
if (distance <= r1 + r2) {
fill(56, 45, 78);
}
circle(x2, y2, r2*2);
pop();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>