working w love.physics

This commit is contained in:
Tangent 2019-06-13 22:09:34 -07:00
parent 8f4a7fe86d
commit d56512e393

View File

@ -1,5 +1,9 @@
import random from love.math
w, h = love.graphics.getDimensions!
world = love.physics.newWorld!
particles = {}
types = setmetatable {}, {
__index: (t, k) ->
t[k] = {
@ -11,25 +15,19 @@ types = setmetatable {}, {
return t[k]
}
class Particle
new: (@x, @y, @vx, @vy, mass) =>
for stat, value in pairs types[mass]
@[stat] = value
update: (dt) =>
@x += @vx * dt
@y += @vy * dt
mk_particle = (x, y, vx, vy, mass) ->
stats = types[mass]
shape = love.physics.newCircleShape stats.radius
body = love.physics.newBody world, x, y, "dynamic"
body\setMass stats.mass
body\applyForce stats.mass * vx, stats.mass * vy
fixture = love.physics.newFixture body, shape
particle = setmetatable{ :body, :fixture }, { __index: stats }
table.insert particles, particle
particles = {}
-- 2 2 -- repel 4 (2 - 2 = 0)
-- 2 -2 -- attract 4 (2 - -2 = 4)
-- -2 2 -- attract 4 (-2 - 2 = -4)
-- -2 -2 -- repel 4 (-2 - -2 = 0)
-- add abs values
do_physics = (A, B, dt) ->
dx = A.x - B.x
dy = A.y - B.y
do_physics = (A, B) ->
dx = A.body\getX! - B.body\getX!
dy = A.body\getY! - B.body\getY!
d2 = dx * dx + dy * dy
a = math.atan2 dy, dx
x = math.cos a
@ -40,23 +38,32 @@ do_physics = (A, B, dt) ->
c *= -1 if (A.charge < 0 and B.charge > 0) or (A.charge > 0 and B.charge < 0)
f = g + c
A.vx -= f * x * dt
A.vy -= f * y * dt
B.vx += f * x * dt
B.vy += f * y * dt
A.body\applyForce -f * x, -f * y
B.body\applyForce f * x, f * y
-- a screen-sized box to keep everything contained
edges = {
left: love.physics.newEdgeShape 0, 0, 0, h
right: love.physics.newEdgeShape w, 0, w, h
top: love.physics.newEdgeShape 0, 0, w, 0
bottom: love.physics.newEdgeShape 0, h, w, h
}
edgeBody = love.physics.newBody world, 0, 0
for _, edge in pairs edges
love.physics.newFixture edgeBody, edge
love.update = (dt) ->
for i = 1, #particles - 1
for j = i + 1, #particles
a, b = particles[i], particles[j]
do_physics a, b, dt
a\update dt
b\update dt
do_physics a, b
world\update dt
love.draw = ->
for particle in *particles
love.graphics.setColor particle.color
love.graphics.circle "fill", particle.x, particle.y, particle.radius
love.graphics.circle "fill", particle.body\getX!, particle.body\getY!, particle.radius
love.mousepressed = (x, y, btn) ->
table.insert particles, Particle(x, y, 0, 0, math.floor 100 * random!)
mk_particle x, y, 0, 0, math.floor 1 + 99 * random!