A particle simulator attempt.

main.moon 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. width, height = love.graphics.getDimensions!
  2. rng = love.math.newRandomGenerator 0
  3. types = 7
  4. radius = 4
  5. colors = {}
  6. interactions = {}
  7. universe = {}
  8. physics = (a, b) ->
  9. dx = a.x - b.x
  10. dy = a.y - b.y
  11. ds = dx * dx + dy * dy
  12. theta = math.atan2 dy, dx
  13. x = math.cos theta
  14. y = math.sin theta
  15. f = interactions["#{a.n}.#{b.n}"](ds)
  16. a.vx += f * x
  17. a.vy += f * y
  18. f = interactions["#{b.n}.#{a.n}"](ds)
  19. b.vx += f * x
  20. b.vy += f * y
  21. for a = 1, types
  22. for b = 1, types
  23. A = rng\randomNormal 0.5, 0
  24. aa = rng\randomNormal 5, 10
  25. B = rng\randomNormal 0.5, 0
  26. bb = rng\randomNormal 5, 10
  27. interactions["#{a}.#{b}"] = (ds) ->
  28. if ds < radius^0.5
  29. return 1 / ds
  30. else
  31. return A * (ds^0.5 - aa)
  32. interactions["#{b}.#{a}"] = (ds) ->
  33. if ds < radius^0.5
  34. return 1 / ds
  35. else
  36. return B * (ds^0.5 - bb)
  37. -- for k,v in pairs interactions
  38. -- print k,v
  39. for a = 1, types
  40. colors[a] = { rng\random!, rng\random!, rng\random!, 1 }
  41. class Particle
  42. new: (@n=1, x, y) =>
  43. @x = x or love.math.random 0, width
  44. @y = y or love.math.random 0, height
  45. @vx = 0
  46. @vy = 0
  47. for i=1, 2
  48. table.insert universe, Particle(love.math.random 1, types)
  49. love.update = (dt) ->
  50. for a = 1, #universe - 1
  51. for b = a + 1, #universe
  52. physics(universe[a], universe[b])
  53. for particle in *universe
  54. particle.vx *= 0.01
  55. particle.vy *= 0.01
  56. particle.x += particle.vx * dt
  57. particle.y += particle.vy * dt
  58. love.draw = ->
  59. for particle in *universe
  60. love.graphics.setColor colors[particle.n]
  61. love.graphics.circle "fill", particle.x, particle.y, radius
  62. love.keypressed = (key) ->
  63. love.event.quit! if key == "escape"