Solution 1 :

Your condition1.js file should look like this. I used the p5.Vector for the circle position, but you can change it if you want. To be clear, the squaring is skipped to make it a bit faster.

function mousePressed(event)
  let distanceX = event.clientX - circlePos.x;
  let distanceY = event.clientY - circlePos.y;

  if (distanceX * distanceX + distanceY * distanceY < (circleRadius * circleRadius))
    document.write("You clicked the circle!");
    document.write("You clicked outside the circle!");

Solution 2 :

function mousePressed()
  if(dist(mouseX,mouseY, Circle.x, Circle.y) <= Circle.Radius)

P5.js has a built in distance function, it uses square root so its a little slow, but it gets the job done.

Problem :

I have used p5.js library in order to make a small circle game.

Circle Game

in which when the user clicks outside the circle, the output is:
Output when mouse is clicked outside the circle

But even when I’m clicking inside the circle, still the output says that I’ve clicked outside the circle.
Mouse inside the circle

here is the index.html file’s code:

<!DOCTYPE html>
    <meta charset="utf-8">
    <title> A Simple Circle Game </title>
    <p style="text-align: center"> A Simple Circle Game </b> </p>
    <script src="[email protected]/lib/p5.js"></script>
    <script type="text/javascript" src="sketch.js"></script>
    <script src="condition1.js"></script>

the sketch.js file is as follow:

function setup(){

function draw() {
  // Draw a circle
  fill(240, 204, 0);
  circle(mouseX, mouseY, 5);

the condition1.js file is as follows:

function mousePressed() {
  dist = Math.sqrt(250 * 250 + 100 * 100);
  if (mouseX > 566  && mouseX < 666 && mouseY < 258  && mouseY > 158 ) {
    document.write("You clicked the circle!");
  } else {
    document.write("You clicked outside the circle!");

In the above code, in the if condition, shall I use any other logic or is there any else issue due to which my game isn’t behaving in the way it ought to be?

I tried changing the dimensions of mouseX and mouseY but all in vain. SSo, I’m expecting a better approach towards my solution.


Comment posted by Epsit

Yeah surely, it’s working now. Thanks but can you explain what do you mean by saying square root makes it slow…? I guess you’re talking about the time it takes when some certain huge input is given to it. Is it so?

Comment posted by MLGMilk

Square root is just overall, a very slow operation. But since you’re not checking the mouse position every frame it should be 100% fine.