Serendipity
Posted by goerp
March 16th, 2013 12:24 pm
I was playing around with an idea for the theme ‘blood in the water’ and was looking for a way to simulate currents in the water.
I will not be using it, but I liked the effect enough to share it.
you can read more about it on my blog

Thanks for sharing!
It’s hard to believe you get such a fluid look just with each cell having a random component. Very cool; I’m filing this away for later.
There isn’t much code needed
this is the code for creating the field:
var field:Vector.<Vector.>=new Vector.<Vector.>;//two dimensional array (y,x)
for (var xF:int=0; xF<Math.floor(stage.stageWidth/fieldSize); xF++){
fieldLine=new Vector.;
for (var yF:int=0; yF<Math.floor(stage.stageHeight/fieldSize); yF++){
fieldLine.push(Math.floor(Math.random()*360)); //random angle
}
field.push(fieldLine);
}
this is the code for the effect on a particle (for every particle every tick):
var xN:int;
var yN:int;
//for the cell and all surrounding cells
for (var dx:int=-1; dx<=1; dx++){
for (var dy:int=-1; dy<=1; dy++){
//xN, yN coordinates of current cell
//xCenter and yCenter are the coordinates of the cell the particle is in.
xN=xCenter+dx;
yN=yCenter+dy;
//wraparound the edges
if (xN<0) xN=field.length-1;
if (yN field.length-1) xN=0;
if (yN> field.length-1) yN=0;
//change speed based on influence of cells
//the center cell will have a normal strength influence
//the surrounding cells will have strength divided by the distance divided by 10
particleSpeed.x+=((dx==0 && dy==0) ? angleSin(field[xN][yN]):angleSin(field[xN][yN]/Math.sqrt(dx*dx+dy*dy)))/10;
particleSpeed.y+=((dx==0 && dy==0) ? angleCos(field[xN][yN]):angleCos(field[xN][yN]/Math.sqrt(dx*dx+dy*dy)))/10;
}
}
//limit the speed to maximum
if(particleSpeed.x>3)particleSpeed.x=3;
if(particleSpeed.x3)particleSpeed.y=3;
if(particleSpeed.y<-3)particleSpeed.y=-3;
//then update position based on speed
s.x+=speed.x;
s.y+=speed.y;
//wraparound edges
if (s.xstage.stageWidth) s.x=0;
if (s.ystage.stageHeight) s.y=0;