![](/img/trans.png)
[英]How do I make the radius of a circle alternate between a bigger and smaller radius in processing in p5.js?
[英]How do you make a circle shaped button in p5.js?
我正在制作一個 p5.js 項目。 在其中,我正在生成一個列表(包含 8 個元素)並將它們設置為 1/0。 每個代表一個位(1,2,4,8,16,32,64,128),如果元素為 1,我添加位數組的索引。
例如i = 3
, states[i] = 1
, bit[i] = 8
所以我將 8 添加到一個數字上,因為該位的當前狀態是 1。
另一件事是它根據位狀態繪制了一個紅色/綠色的圓圈。
現在您已經了解了基本概念,我想添加讓用戶按下圓圈來更改其狀態的功能(從 1 到 0 以及從 0 到 1)。 我知道如何改變狀態,但我如何測試用戶是否真的按下了按鈕(注意按鈕是一個圓圈)?
到目前為止,這是我的代碼:
var array = [0,1,0,1,1,1,1,1];
var values = [128,64,32,16,8,4,2,1];
function setup(){
//console.log(array);
createCanvas(600,600);
textStyle(BOLDITALIC);
textSize(50);
}
function draw(){
clear();
var a = calculate(array);
background(51);
fill(255);
text(a,250,500);
let crcl = 50;
let d = 20;
let r = d/2;
for (let i = 0; i < 8; i++){
}
for (let i = 0; i < 8; i++){
if (array[i] === 1){
fill(0,255,0);
circle(crcl, 50, d);
} else {
fill(255,0,0);
circle(crcl, 50, d);
}
crcl += 50;
}
}
function calculate(array){
let a = 0;
for (let i = 0; i < 8; i++){
if (array[i] === 1){
a += values[i];
}
}
return a;
}
我為所有只想查看代碼的人完成的代碼!:
var array = [0,1,0,1,1,1,1,1];
var values = [128,64,32,16,8,4,2,1];
var positonsX = [50,100,150,200,250,300,350,400];
var crcl = 50;
var d = 20;
var r = d/2;
function setup(){
//console.log(array);
createCanvas(600,600);
textStyle(BOLDITALIC);
textSize(50);
}
function draw(){
clear();
let crcl = 50;
d = 20;
r = d/2;
a = calculate(array);
background(51);
fill(255);
text(a,250,500);
for (let i = 0; i < 8; i++){
if (array[i] === 1){
fill(0,255,0);
circle(crcl, 50, d);
} else {
fill(255,0,0);
circle(crcl, 50, d);
}
crcl += 50;
}
}
function calculate(array){
let a = 0;
for (let i = 0; i < 8; i++){
if (array[i] === 1){
a += values[i];
}
}
return a;
}
function mouseClicked(){
for (let i = 0; i < 8; i++){
if (dist(mouseX,mouseY,positonsX[i],50) <= d){
array[i] = 1 - array[i];
}
}
}
您可以通過比較點與圓心之間的距離並將其與圓的半徑進行比較來檢測點(在您的情況下, mouseX, mouseY
)是否在圓中。 如果距離小於半徑,則該點在圓內。
您可以在谷歌上搜索“檢測點是否在圓內”以獲得大量結果。 無恥的自我推銷:本教程解釋了碰撞檢測,包括點圓碰撞檢測。
我會檢查 mouseClicked ( https://p5js.org/reference/#/p5/mouseClicked ),然后是 mouseX, mouseY 以查看是否點擊了一個圓圈。
我為我的一個項目創建了這個類來添加圓形按鈕。 共享草圖的鏈接,可能會節省其他人一些時間:p5.js web editor sketch
檢查鼠標指針是否在一個圓圈內:
獲取圓心到鼠標指針的距離
const distance = dist(circleX, circleY, mouseX, mouseY)
如果該距離小於圓的半徑,則鼠標在圓內
const isInside = (distance < circleRadius)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.