I have used p5.js library in order to make a small circle game.
in which when the user clicks outside the circle, the output is:
But even when I'm clicking inside the circle, still the output says that I've clicked outside the circle.
here is the index.html
file's code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> A Simple Circle Game </title>
</head>
<body>
<p style="text-align: center"> A Simple Circle Game </b> </p>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.js"></script>
<script type="text/javascript" src="sketch.js"></script>
<script src="condition1.js"></script>
</body>
</html>
the sketch.js
file is as follow:
function setup(){
createCanvas(500,200).center();
noStroke();
background(230);
circle(250,100,100);
}
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.
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!");
}
else
{
document.write("You clicked outside the circle!");
}
}