英文:
How to change the color of a PShape on key press?
问题
我正在尝试在按下键时更改PShape的颜色,以作为按下该键的标记。是否有一种方法可以在不使用beginShape()
和endShape()
以及新的填充重新定义PShape的情况下实现这一点?
以下是我尝试的示例:
PShape s;
void setup() {
size(100, 100);
s = createShape(RECT, 25, 25, 50, 50);
s.setFill(color(75, 183, 19));
shape(s);
}
void draw() {
if (keyPressed == true) {
if (key == 'w') {
s.setFill(color(217, 93, 47));
}
}
}
setFill()
函数在将形状放入窗口之前起作用,但在draw()
函数中不起作用。我还尝试使用fill()
。
我还尝试在声明形状并在重新绘制形状之前更改填充时使用disableStyle()
:
PShape s;
void setup() {
size(100, 100);
shape();
fill(75, 183, 19);
shape(s);
}
void draw() {
if (keyPressed == true) {
if (key == 'w') {
fill(217, 93, 47);
shape();
}
}
}
void shape() {
s = createShape(RECT, 25, 25, 50, 50);
s.disableStyle();
}
这也不起作用,形状仍然保持为第一种颜色。我是否遗漏了任何函数可以帮助我实现这一点?
英文:
I am trying to change the color of a PShape when I press a key, as a marker that that key is pressed. Is there a way that I can do this without redefining the PShape using beginShape()
and endShape()
with a new fill every time?
Here is an example of what I am attempting to do:
PShape s;
void setup() {
size(100,100);
s = createShape(RECT,25,25,50,50);
s.setFill(color(75,183,19));
shape(s);
}
void draw() {
if(keyPressed == true) {
if(key == 'w') {
s.setFill(color(217,93,47));
}
}
}
the setFill()
function works before I actually put the shape into the window, but it won't in the draw()
function. I have also tried using fill()
.
I have also tried using disableStyle()
when declaring the shape and changing the fill before redrawing the shape:
PShape s;
void setup() {
size(100,100);
shape();
fill(75,183,19);
shape(s);
}
void draw() {
if(keyPressed == true) {
if(key == 'w') {
fill(217,93,47);
shape();
}
}
}
void shape() {
s = createShape(RECT,25,25,50,50);
s.disableStyle();
}
This also doesn't work, the shape just stays as the first color. Is there any function I am missing which will help me to achieve this?
答案1
得分: 0
以下是代码的翻译部分:
PShape s;
color chosenColor;
void setup() {
size(100,100);
chosenColor = color(random(255), random(255), random(255));
}
void draw() {
myShape();
}
void myShape() {
s = createShape(RECT,25,25,50,50);
s.setFill(chosenColor);
shape(s);
}
void keyPressed() {
if (key == 'w') {
chosenColor = color(random(255), random(255), random(255));
}
}
英文:
The following code will change the color of a PShape square each time a designated key is pressed:
PShape s;
color chosenColor;
void setup() {
size(100,100);
chosenColor = color(random(255), random(255), random(255));
}
void draw() {
myShape();
}
void myShape() {
s = createShape(RECT,25,25,50,50);
s.setFill(chosenColor);
shape(s);
}
void keyPressed() {
if (key == 'w') {
chosenColor = color(random(255), random(255), random(255));
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论