-- Physics
CONST_G = 1 -- <<< 6.6738 * 10 ^ (-11) >>> m^3 / (kg s^2) "Gravitational constant"
function setup()
displayMode(OVERLAY)
particles = {}
_gId = 1 -- Global Id
for i = 1, 50 do
local p = Particle()
p.pos.x, p.pos.y = math.random(0, WIDTH), math.random(0, HEIGHT)
table.insert(particles, p)
end
end
function draw()
background(0)
for a, b in ipairs(particles) do
b:draw()
b:update()
end
end
-- Particle class
Particle = class()
function Particle:init()
self.id = _gId
_gId = _gId + 1
-- Attributes
self.mass = 1
self.color = color(255)
self.size = 5
-- Position
self.pos = vec2(0, 0) -- pixels
self.speed = vec2(0, 0) -- pixels / frame
self.acc = vec2(0, 0) -- pixels / frame ^ 2
end
function Particle:draw()
resetStyle()
fill(self.color)
ellipse(self.pos.x, self.pos.y, self.size)
end
function Particle:update()
v = vec2(0, 0)
-- Calculate acceleration
for a, b in ipairs(particles) do
if not (self.id == b.id) then
--[[ Speed:
r = math.sqrt((self.pos.x - b.pos.x)^2 + (self.pos.y - b.pos.y)^2)
F = self.mass * b.mass / r^2
a = F / self.mass]]
-- Average speed
local a = CONST_G * b.mass / ((self.pos.x - b.pos.x)^2 + (self.pos.y - b.pos.y)^2)
-- ?y / ?x
local m = (self.pos.y - b.pos.y)/(self.pos.x - b.pos.x)
-- y = mx + t - a line between both points
local t = m * self.pos.x - self.pos.y
v = v + vec2(.0001, m * self.pos.x + t)
end
end
-- Update parameters
self.pos = self.pos + self.speed
self.speed = self.speed + self.acc
self.acc = v
if self.id == 5 then
print(self.pos, self.speed, self.acc)
end
end
@TokOut Comment out the last print statement and it won’t crash. Your values are way out of wack for self.pos, self.speed, self.acc . Here’s some values before it crashes. You need to recheck your calculations.
(623.852200, -28921982519067048803797183765449539584.000000)
(0.137200, -1574872098314025940019901817338323795968.000000)
(0.004900, -27882067698290623052232668640255068340224.000000)