(I don't mean that subtracting gives a different mathematical result than addition-that's obvious) I'm trying to make a particle simulator game, and I ran into a weird phenomenon. (I'm using javascript with javap5.js). In the draw function, I have a function that test if the space below a particle is empty, and if it is, it moves down by one pixel(or adding one to the result-that's where the addition is) The only issue is, instead of a gradual change when going down, it INSTANTLY goes to the bottom of the screen. When I use subtraction instead(so gravity is up) it behaves as expected and goes up gradually. Here's the function I'm talking about(game is the array of particles)-
function updateParticles() {
for(var i = 0; i<250; i++) {
for(var i2 = 0; i2<250; i2++) {
if(game[i][i2] == 1) {
if(game[i][i2+1] == 0) {
game[i][i2]=0;
game[i][i2+1]=1;
}
}
}
}
}
and here is the whole thing(jsfiddle)- https://jsfiddle.net/gwood5901/trm6xLv8/
Your for
loops are going from left to right, top to bottom. Here's a simplified model of what is happening:
i = 0;
[ 1 ] <-- Is this a one?
[ 0 ] <-- And is this a zero?
[ 0 ]
YES
SWAP
[ 0 ] <-- prev 1
[ 1 ] <-- prev 0
[ 0 ]
i = 1;
[ 0 ]
[ 1 ] <-- Is this a one?
[ 0 ] <-- And is this a zero?
YES
SWAP
[ 0 ]
[ 0 ] <-- prev 1
[ 1 ] <-- prev 0
And that all happens at once in one call of the function.
With the subtraction:
i = 0;
[ 0 ] <-- Is this a zero?
[ 0 ] <-- And is this a one?
[ 1 ]
NO
DO NOTHING
i = 1;
[ 0 ]
[ 0 ] <-- Is this a zero?
[ 1 ] <-- And is this a one?
YES
SWAP
[ 0 ]
[ 1 ] <-- prev 0
[ 0 ] <-- prev 1
And on the second function call:
i = 0;
[ 0 ] <-- Is this a zero?
[ 1 ] <-- And is this a one?
[ 0 ]
YES
SWAP
[ 1 ] <-- prev 0
[ 0 ] <-- prev 1
[ 0 ]
i = 1;
[ 1 ]
[ 0 ] <-- Is this a zero?
[ 0 ] <-- And is this a one?
NO
DO NOTHING
This can be fixed two ways: a buffer or just traversing the array backwards.
Here's the simple way of just traversing the array backwards:
function {
for(var i = 250-1; i >= 0; i--) {
for(var i2 = 250-2; i2 >= 0; i2--) {
if(game[i][i2] == 1) {
if(game[i][i2+1] == 0) {
game[i][i2]=0;
game[i][i2+1]=1;
}
}
}
}
}
Here's a JSFiddle with the updateParticles()
function changed to this: https://jsfiddle.net/Lhqgujxt/