我正在寻找一些帮助,可以使用Processing
函数随机化Array
上的特定颜色。例如,我只希望颜色是专门的red, blue, yellow and green
。如何确保当每个字母从墙上反弹时,字母的颜色会变为其中一种颜色?
以下是我的代码,非常感谢帮助。
String word = "bounce";
char[] letters;
ArrayList<Letter> letterObjects;
boolean ballFall = false;
PFont font;
color randColour = color (0);
Letter l;
void setup () {
size (500, 500);
pixelDensity(displayDensity());
textAlign(CENTER);
textSize(30);
letters = word.toCharArray();
letterObjects = new ArrayList<Letter>();
font = createFont("AvenirNext-Medium", 50);
textFont(font);
//iterate over the letter array
//for each letter create a new object
//add this object to an ArrayLost
for (int i = 0; i<letters.length; i++) {
char currentLetter = letters[i];
float currentPosition = i * 30;
letterObjects.add(new Letter(currentLetter, 180 + currentPosition, height/2));
}
}
void draw () {
background(255);
for (Letter l : letterObjects) {
l.display();
}
if (ballFall == true) {
for (Letter l : letterObjects) {
l.move();
l.bounce();
}
}
}
void mouseClicked() {
ballFall = true;
}
信件类
class Letter {
char character;
float x, y;
float xSpeed, ySpeed;
float distance;
Letter(char _c, float _x, float _y) {
character = _c;
x = _x;
y = _y;
//x = random(width);
//y = random(height);
xSpeed = random(1, 3);
ySpeed = random(1, 3);
}
void move () {
x += xSpeed*2;
y += ySpeed*2;
}
void bounce () {
if (x<0 || x>width) {
xSpeed *=-1;
randColour = color (random(255), random (255), random(255));
}
if (y<0 || y>height) {
ySpeed *=-1;
randColour = color (random(255), random (255), random(255));
}
}
void display () {
fill(randColour);
text(character, x, y);
}
}
答案 0 :(得分:0)
列出您想要选择的颜色
color red = #FF0000;
color blue = #0000FF;
color yellow = #FFFF00;
color green = #00FF00;
color[] colors = { red, blue, yellow, green };
然后使用random
方法选择数组中的索引。并使用该索引处的颜色:
对于您的情况,您可以这样写下您的Letter类: 假设使用Letter类的其余代码正常工作
class Letter {
char character;
float x, y;
float xSpeed, ySpeed;
float distance;
// Declare the colors you want to use in a an array
color red = #FF0000;
color blue = #0000FF;
color yellow = #FFFF00;
color green = #00FF00;
color[] colors = { red, blue, yellow, green };
color randColor;
Letter(char _c, float _x, float _y) {
character = _c;
x = _x;
y = _y;
//x = random(width);
//y = random(height);
xSpeed = random(1, 3);
ySpeed = random(1, 3);
// Pick a random initial color
randColor = colors[int(random(colors.length))];
}
void move () {
x += xSpeed*2;
y += ySpeed*2;
}
void bounce () {
if (x<0 || x>width) {
xSpeed *= -1;
// Pick a random color
randColor = colors[int(random(colors.length))];
} else if (y<0 || y>height) {
ySpeed *= -1;
// Pick a random color
randColor = colors[int(random(colors.length))];
}
}
void display () {
fill(randColor);
text(character, x, y);
}
}