I have the following code in C++ from a book/tutorial on OpenGL:
for (int i = 0; i < 256; i++)
{
droplet_x_offset[i] = random_float() * 2.0f - 1.0f;
droplet_rot_speed[i] = (random_float() + 0.5f) * ((i & 1) ? -3.0f : 3.0f);
droplet_fall_speed[i] = random_float() + 0.2f;
}
Now I have tried to convert it to Java, and mostly it is trivial:
Random random = new Random();
for (int i = 0; i < 256; i++) {
dropletXSpeed[i] = random.nextFloat() * 2.0f - 1.0f;
dropletRotSpeed[i] = (random.nextFloat() + 0.5f) * ((i & 1) ? -3.0f : 3.0f);
dropletFallSpeed[i] = random.nextFloat() + 0.2f;
}
Except that ((i & 1) ? -3.0f : 3.0)
is not accepted by Java with the message:
incompatible types: int cannot be converted to boolean .
Can someone explain me what ( i & 1
) exactly does and how should it be replaced in Java?
Unlike C/C++, in Java conditionals have to evaluate to a boolean.
For example:
int i = 1;
if (i) { ... }
isn't valid in java.
Your ternary would need to be:
(i & 1) != 0 ? -3.0f : 3.0f;
Using a trigraph is not as efficient as a formula for simple cases. This is because a branch miss is so expensive. You can do the same like this.
(3 - 6 * (i & 1))
This will be 3 if i
is even and -3 if it is odd.
Note: as you have a loop there is an even simpler solution.
for (int i = 0; i < 256; i += 2) {
dropletXSpeed[i] = random.nextFloat() * 2.0f - 1.0f;
dropletXSpeed[i+1] = random.nextFloat() * 2.0f - 1.0f;
dropletRotSpeed[i] = (random.nextFloat() + 0.5f) * 3.0f;
dropletRotSpeed[i+1] = (random.nextFloat() + 0.5f) * -3.0f;
dropletFallSpeed[i] = random.nextFloat() + 0.2f;
dropletFallSpeed[i+1] = random.nextFloat() + 0.2f;
}
BTW nextFloat() is reasonably expensive. If you don't need 24-bit of randomness you can try something like this.
public float next8bitFloat() {
return random.nextInt(256) * (1.0 / 256);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.