Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
Circle/circle collision fires up before the circles are colliding

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:

enter image description here enter image description here

As you can see, the collision detection fires up way before there is any contact, and I have no idea why.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The 3nd 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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!