# Brownian motion (kind of)

I was just messing around with a program, trying some stuff, and it started to remind me of Brownian motion. So I added more code to get this. It kind of starts out slow, but every time the red ball gets hit, another random blue ball is created. I put a 250 ball limit on this because the first time I ran it, it crashed because it created too many balls. Once all 250 balls are created, it kind of shows the Brownian motion. It also shows the ball count in the middle of the screen. Increasing the friction will cause things to slow down eventually.

``````
supportedOrientations(PORTRAIT)

-- Brownian motion (kind of)
--# Main

function setup()
displayMode(FULLSCREEN)

tab={}                    -- table for balls

create()
end

-- set up the edge lines
line1 = physics.body(EDGE,vec2(5,5),vec2(5,HEIGHT-5))
line2 = physics.body(EDGE,vec2(WIDTH-5,5),vec2(WIDTH-5,HEIGHT-5))
line3 = physics.body(EDGE,vec2(5,5),vec2(WIDTH-5,5))
line4 = physics.body(EDGE,vec2(5,HEIGHT-5),vec2(WIDTH-5,HEIGHT-5))
end

function create()    -- create a new ball in the table
local a=#tab+1

if a > 250 then  -- don't exceed 250 balls
return
end

-- set values for new balls
tab[a] = physics.body(CIRCLE,10)
tab[a].mass=2
tab[a].friction=0
tab[a].x=math.random(30,WIDTH-30)
tab[a].y=math.random(30,HEIGHT-30)
tab[a].gravityScale=0
tab[a].restitution=1
tab[a].linearVelocity=vec2(math.random(400),math.random(400))
end

function collide(contact)
if contact.state == BEGAN then
-- if the red ball is hit, create another ball and sound
if contact.bodyA.x == tab[1].x and
contact.bodyA.y == tab[1].y then
create()
sound(SOUND_HIT,50)
end
end
end

function draw()
background(50, 50, 50)

-- show the number of balls in the center of the screen
fill(255)
text(#tab,WIDTH/2,HEIGHT/2+20)

-- draw all of the balls
strokeWidth(0)
for z=1,#tab do
fill(0, 47, 200, 255)    -- color of the blue balls
if z == 1 then           -- color of the red ball
fill(255,0,0)
end
ellipse(tab[z].x,tab[z].y,20,20)
end

-- draw the edge lines
stroke(255)
strokeWidth(5)
line(5,5,5,HEIGHT-5)
line(WIDTH-5,5,WIDTH-5,HEIGHT-5)
line(5,5,WIDTH-5,5)
line(5,HEIGHT-5,WIDTH-5,HEIGHT-5)
end

``````

Wow! Wonderful example!
I mean, I come from the CFD area (Computational Fluid Dynamics), trying to explore my field from other points of view. I enjoy a lot the iPad and the games made for it, especially the ones made with a fine physics engine. Now, that I’m able to see from a very comfortable side, thanks Codea, what is all behind when making games, I doubly appreciate when the games-physics-engines (originated from fields like mine) are employed to “real” world problems in such an easy way, that… it spares (at least for proof of concepts), if not months, weeks of painful programing. :(|)
Anyway, thanks to TLL and all of you, Codea-guys, for doing such a tremendous work.
Saludos,
Victor ~O)