有没有办法检查鼠标是否在 p5.js 中的某个元素上单击

Is there a way to check if the mouse is clicked on a certain element in p5.js

所以我想做的是制作一个唱首歌游戏,但是当我使用标准时:

let Coins = 0;

function setup() {
  createCanvas(400, 400)
}
//draws the circle
function draw() {
  background(100)
  circle(200, 200, 50)
  //creates the text to show the amount of coins
  text(Coins, 200 - (textWidth(Coins) / 2), 150)
}
//detects when the mouse is pressed
function mouseClicked() {
  //changes the number of coins
  Coins = Coins + 1
}
<!DOCTYPE html>
<html lang="en">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
  <link rel="stylesheet" type="text/css" href="style.css">
  <meta charset="utf-8" />

</head>

<body>
  <script src="sketch.js"></script>
</body>

</html>

我可以点击任何地方,它会计算硬币数,但我想要这样,如果鼠标在 shape/element 上,它就会计算。 我不想使用“If (mouseX => width / 2)”但只知道鼠标何时 over/hovering 在元素上。

在 p5js 中你需要自己实现 "hit testing"。在这种情况下,您可以通过检查鼠标与硬币中心之间的距离是否小于硬币的半径来实现。

let Coins = 0;

function setup() {
  createCanvas(400, 400)
}

let coinPosition = new p5.Vector(200, 200);
let coinRadius = 25;

//draws the circle
function draw() {
  background(100)
  push()
  if (dist(mouseX, mouseY, coinPosition.x, coinPosition.y) <= coinRadius) {
    fill('gold')
  }
  circle(coinPosition.x, coinPosition.y, coinRadius * 2)
  // restore the previous fill value
  pop()
  //creates the text to show the amount of coins
  text(Coins, 200 - (textWidth(Coins) / 2), 150)
}
//detects when the mouse is pressed
function mouseClicked() {
  if (dist(mouseX, mouseY, coinPosition.x, coinPosition.y) <= coinRadius) {
    //changes the number of coins
    Coins = Coins + 1
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
  <link rel="stylesheet" type="text/css" href="style.css">
  <meta charset="utf-8" />

</head>

<body>
  <script src="sketch.js"></script>
</body>

</html>