Guest program: bouncing balls


I just received a very fun program from Origedit. Enjoy!

g=love.graphics
rnd=math.random
bs={}
bs.gravity=10
function addb()
 local function dir()
  return (rnd()*2-1)*200
 end
 table.insert(bs,{
  x=rnd()*Safe_width,
  y=rnd()*Safe_height,
  sx=dir(), sy=dir(),
  r=20+rnd()*50,
  col={rnd(),rnd(),rnd()}
 })
end
for i=1,30 do addb() end
function movep(b,dt,p,s,max)
 b[p]=b[p]+b[s]*dt
 if b[p] < b.r then
  b[p]=b.r
  b[s]=math.abs(b[s])
 elseif b[p] > max-b.r then
  b[p]=max-b.r
  b[s]=-math.abs(b[s])
end end
function bdist(a,b)
 return math.pow(math.pow(a.x-b.x,2)+math.pow(a.y-b.y,2),0.5)
end
function bbounce(b, bb,d)
 local dx,dy=b.x-bb.x,b.y-bb.y
 local k=
  ((b.sx-bb.sx)*dx+
  (b.sy-bb.sy)*dy)/
  d/d
 local h=-(d-b.r-bb.r)/d/2
 return b.sx-dx*k,b.sy-dy*k,b.x+dx*h,b.y+dy*h
end
function bcollide(b,i)
 for ii=i+1,#bs,1 do
  local bb=bs[ii]
  local d=bdist(b,bb)
  if d < b.r+bb.r then
   local vx,vy,x,y=bbounce(b,bb,d)
   bb.sx,bb.sy,bb.x,bb.y=bbounce(bb,b,d)
   b.sx,b.sy,b.x,b.y=vx,vy,x,y
end end end
function car.update(dt)
 for i,b in ipairs(bs) do
  movep(b,dt,"x","sx",Safe_width)
  movep(b,dt,"y","sy",Safe_height)
  b.sy=b.sy+bs.gravity
  bcollide(b,i)
end end
function car.draw()
 for i,b in ipairs(bs) do
  g.setColor(b.col)
  g.circle("fill",b.x,b.y,b.r)
end end

If you have built anything with Lua Carousel and would like to show it here, please do what Origedit did, and send me a message.

Files

carousel-bj.love 118 kB
24 days ago
carousel-bj-safe.love 118 kB
24 days ago

Get Lua Carousel

Leave a comment

Log in with itch.io to leave a comment.