We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I am making a physics simulator and so far I have implemented water particles. But when they hit an object the are supposed to move in a random x direction, as long as it is an empty cell. But it only moves left, -x. I cannot figure out why. It would be appreciated if someone could help.
Here's my code:
int[] water = new int[100000];
int[] sand = new int[0];
int x;
int y;
int longestArray;
int waterCount = 0;
void setup() {
background(0);
size(600,600);
noStroke();
fill(162,137,52);
rect(220,400,100,2);
}
void draw() {
longestArray = max(water.length/2, sand.length/2);
for (int currentParticle = 0; currentParticle < longestArray; currentParticle++) {
if (currentParticle <= waterCount) {
x = water[currentParticle*2];
y = water[currentParticle*2+1];
fill(0,0,0);
rect(x,y,1,1);
if (get(x,y+1) != color(0)) {
int randomDirection = int(random(0,1))*2-1;
if (get(x+randomDirection,y) == color(0,0,0)) {
x = x + randomDirection;
} else if (get(x-randomDirection,y) == color(0,0,0)) {
x = x - randomDirection;
}
} else {
y++;
}
fill(0,0,255);
rect(x,y,1,1);
water[currentParticle*2] = x;
water[currentParticle*2+1] = y;
}
}
if (mousePressed == true) {
water[waterCount*2] = mouseX;
water[waterCount*2+1] = mouseY;
waterCount++;
}
}
The issue is with this:
if (get(x,y+1) != color(0)) {
int randomDirection = int(random(0,1))*2-1;
if (get(x+randomDirection,y) == color(0,0,0)) {
x = x + randomDirection;
} else if (get(x-randomDirection,y) == color(0,0,0)) {
x = x - randomDirection;
}
Thanks
EDIT: The post keeps changing the format so some of the code is not in the box...
Answers
When posting code, select it and use the "C" button to format it w/ 4 spaces! ~:>
Hi Zabuza,
I tried your code and from what I can see, your water does go positive (to the right) sometimes, I even saw a few droplets go off the right side of the platform, seems to match your random bit, but then they keep trying to go to the left.
It seems to me, that once your droplet has picked a direction, it doesn't need to keep checking which direction to go.
It may make sense to break off your particles into their own class. Then you can calculate the direction they should be traveling just once, and continue that direction. It should improve the performance of the sketch quite a bit too.
Hope this helps! ak
i'd put this in a loop with a println and see what you get...
(top value is exclusive so your int(random(0, 1)) call will only ever return 0)
Thanks, I figured it out before I saw your post koogs. Using a 2 instead of a 1 for the random seems to fix the issue. int(random(2))*2-1;