A demo I coded up for a friend.
`%Project Title%
`%Source File Name%
`======================
type vec
x as float
y as float
endtype
type particle
pos as vec
vel as vec
mass as float
endtype
dim particles(0) as particle
particles(0).pos.x=screen width()/2
particles(0).pos.y=screen height()/2
particles(0).vel.x=10
particles(0).vel.y=10
particles(0).mass=1
global timestep as float
global curtime as integer
curtime=timer()
timestep=.001
for n=0 to 20
addParticle(rnd(screen width()),rnd(screen height()),20)
next n
do
timestep=(timer()-curtime)/1000.0
curtime=timer()
inc particles(0).vel.x,(rightkey()-leftkey())*.01
inc particles(0).vel.y,(downkey()-upkey())*.01
drawParticles()
updateParticle()
sync
loop
function updateParticle()
xf as float //actually acceleration
yf as float
xf=0
yf=0
for n=1 to array count(particles())
//get the distance between two particles
dist2#=distance2(particles(0).pos.x,particles(0).pos.y,particles(n).pos.x,particles(n).pos.y)
//force=mass/distance^2
force#=particles(n).mass/dist2#
//get the vector from particle 0 to particle n
dx#=particles(n).pos.x-particles(0).pos.x
dy#=particles(n).pos.y-particles(0).pos.y
//normalize. direction from particle 0 to particle n.
dx#=dx#/sqrt(dist2#) //normalized
dy#=dy#/sqrt(dist2#)
//scale by force and add to the sum of forces.
xf=xf+dx#*force#
yf=yf+dy#*force#
next n
//vel+=force/mass with mass=1 so just add force.
inc particles(0).vel.x,xf
inc particles(0).vel.y,yf
//P+=V*dt
particles(0).pos.x=particles(0).pos.x+particles(0).vel.x*timestep
particles(0).pos.y=particles(0).pos.y+particles(0).vel.y*timestep
//keep the particle bound on the screen.
if particles(0).pos.x<0
particles(0).pos.x=0
particles(0).vel.x=0 //zero x axis velocity
endif
if particles(0).pos.x>screen width()
particles(0).pos.x=screen width()
particles(0).vel.x=0
endif
if particles(0).pos.y<0
particles(0).pos.y=0
particles(0).vel.y=0
endif
if particles(0).pos.y>screen height()
particles(0).pos.y=screen height()
particles(0).vel.y=0 //zero y axis velocity
endif
endfunction
function distance2(x1 as float, y1 as float, x2 as float, y2 as float)
dx#=x1-x2
dy#=y1-y2
d2#=dx#*dx#+dy#*dy#
endfunction d2#
function drawParticles()
ink rgb(255,0,0),0
circle particles(0).pos.x,particles(0).pos.y,particles(0).mass
ink rgb(255,255,255),0
for n=1 to array count(particles())
circle particles(n).pos.x,particles(n).pos.y,particles(n).mass
next n
endfunction
function addParticle(x as float, y as float, mass as float)
array insert at bottom particles()
index=array count(particles())
particles(index).pos.x=x
particles(index).pos.y=y
particles(index).vel.x=x
particles(index).vel.y=y
particles(index).mass=mass
endfunction
Arrowkeys accelerate the particle.