如何在p5.js中实现圆形按钮及点击状态切换功能?
Got it, let's break down how to solve your problem of detecting clicks on those circular buttons and toggling their states. The key part is checking if the mouse click falls within the bounds of each circle, which we can do using p5.js's built-in dist() function.
Here's the complete working code with explanations:
var array = [0,1,0,1,1,1,1,1]; var values = [128,64,32,16,8,4,2,1]; var positionsX = [50,100,150,200,250,300,350,400]; // Store each circle's x-center var d = 20; // Diameter of the circles var r = d/2; // Radius (for precise click detection) function setup(){ createCanvas(600,600); textStyle(BOLDITALIC); textSize(50); } function draw(){ background(51); let currentTotal = calculate(array); // Display the calculated total fill(255); text(currentTotal, 250, 500); let crclX = 50; // Draw each circle based on its state for (let i = 0; i < 8; i++){ fill(array[i] === 1 ? color(0,255,0) : color(255,0,0)); circle(crclX, 50, d); crclX += 50; } } // Calculate the sum of values where the bit is 1 function calculate(array){ let total = 0; for (let i = 0; i < 8; i++){ if (array[i] === 1){ total += values[i]; } } return total; } // Handle mouse clicks to toggle circle states function mouseClicked(){ for (let i = 0; i < 8; i++){ // Check if the click is within the circle's bounds // dist(mouseX, mouseY, circleX, circleY) <= radius if (dist(mouseX, mouseY, positionsX[i], 50) <= r){ array[i] = 1 - array[i]; // Toggle state: 0 ↔ 1 } } }
Key Details:
- Tracking Circle Positions: The
positionsXarray stores the x-coordinate of each circle's center, making it easy to reference each button's location during click checks. - Click Detection Logic: In
mouseClicked(), we loop through each circle and usedist()to measure the distance between the click point and the circle's center. If this distance is ≤ the circle's radius (r), the click is inside the button. - State Toggle:
array[i] = 1 - array[i]is a clean way to flip the state—turning 0 to 1 and 1 to 0 without extra conditionals. - Visual Feedback: The
draw()function uses green for active (1) states and red for inactive (0) states, updating the displayed total each frame based on the current bit states.
Quick Note:
In your initial final code, you used dist(...) <= d (diameter) instead of the radius. This makes the clickable area twice as large as the visible circle. Using the radius ensures clicks only register when the user taps directly on the circle itself.
内容的提问来源于stack exchange,提问作者CppPythonDude
相关产品推荐
相关产品推荐

