Am I dumb or is this a bug?

void setup() {

void draw() {
  fill((frameCount < 60) ? random(255) : color(255, 0, 0));
  rect(0, 0, width, height);
  fill(color(255, 0, 0));
  text("a", width/2, height/2);

By all means of logic the screen should turn red after 60 frames, but it doesn’t. This is super weird, because the code for the text fill works just fine. So it seems like the structure fill(color(…)) stops working if you include a ternary operand or something? It’s also broken for other similar functions, such as background().

1 Like

I think I understand what is happening. random(255) gives a float, while color(255,0,0) gives an int. The thing is that Processing’s color type is actually an int - for proof, compile and then go to the source/ file inside any of the compiled folders, and see that all color variable declarations turn into int.

Anyways, I think that the ternary operator doesn’t want to give 2 different types of output based on the condition, so it just converts all to float - then, fill() tries to understand float(color(255,0,0)), and interprets it as black.

In other words, use round(random(255)) instead so the result of that ternary operator is always int.


I problem is not caused by the ternary statement because if you change the first line of draw() to

fill((frameCount < 60) ? color(random(255)) : color(255, 0, 0, 255));

and it works just fine.

Still doesn’t answer why the fill color is not red after 60 frames.

@Architector_4 what a good answer, didn’t think of that

For a 0-255 range gray color, (int) random(256) also works. :smiley:

Using round(random(255)), each value within the range 1-254 got the same weight to happen. :thinking:

However, the values 0 & 255 both got half the change to happen compared to the 1-254 range. :crazy_face:

1 Like

True… At that rate, you could also use floor(random(256))

That is until it rolls exactly 256.000 and you are left wondering what in the world has just happened! :o

So, min(floor(random(256)),255) seems to be the best way around for doing this? :v

But that makes it unfair to numbers, as, for example, it can be any number including and between 3 and 4, but it can’t be any number including and between 255 and 256! So, 255 gets whatever-is-floating-point-error-at-that-point less chance ! ! !

Theoretically, that should never happen. For range 0 - 256, 0 is inclusive and 256 is exclusive. :face_with_monocle:

B/c (int) is a cast operator, and floor() is a function, performance-wise, (int) random(256) is faster.

Also, the (int) cast operator simply truncates the value, removing any fractional value past the ..

While floor() skips to the next lowest whole value.
That is, floor(1.5) returns 1. But floor(-1.5) returns -2! :woozy_face:

So I guess the simple answer is don’t let the code cast a color into a float.