#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

# Code crashes codea

Mod
Posts: 889
```-- 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
```