Another case for vectors!
First the code:
Code: Select all
for a=1,30 do
local p = blackhole[1].particle[a] -- makes the code clearer
local dx,dy = -p.x, -p.y -- direction to the black hole
local len = math.sqrt(dx * dx + dy * dy)
-- normalize direction vector
dx,dy = dx / len, dy / len
p.direction = math.atan2(p.y,p.x) -- only needed for drawing stuff
p.speed = len/200
p.x = p.x + dx * p.speed
p.y = p.y + dy * p.speed
end
...then the explanation:
- black_hole.png (23.9 KiB) Viewed 3343 times
Each particle has the position \(\mathbf{p} = (x,y)\) relative to the black hole position
b. To get the directional vector from
p to
b, you simply have to subtract
p from
b. Since the particle position is relative to the black hole,
b is the 0-vector and the result is simply \(\mathbf{d} = \mathbf{b} - \mathbf{p} = (-x,-y)\) (note: you could also define the particles in absolute coordinates, the formula is still valid, but with \(\mathbf{d} = (b_x - x, b_y - y)\)).
If you move the particle by
d, it will end up in the black hole itself, but you want to give it a speed relative to it's distance to the black hole. This is done in a two way process:
To get just the direction of travel, you have to normalize
d, which is a fancy word for making it has a length of 1 by dividing the vector's components by the length. The length of
d (the distance to the black hole) is calculated as \(l = \sqrt{(-x)^2 + (-y)^2}\), so the normalized vector is calculated as \(\mathbf{d}_1 = (x / l, y / l)\).
By multiplying the normalized vector (which is just the
direction of travel) with some number, and adding that result to the position, you can move the particle closer to the black hole.
Edit: Moving the particles in a spiral around the black hole is a little more difficult. Each particle will need to have a velocity vector, which defines the next position. Instead of moving the particle in direction of
d * speed, you have to
add it to the velocity. In fancy physics terms, this is the same as a force acting on the particle in the direction of the black hole. Code wise:
Code: Select all
for a=1,30 do
local p = blackhole[1].particle[a]
local dx,dy = -p.x, -p.y
local len = math.sqrt(dx * dx + dy * dy)
dx,dy = dx / len, dy / len
local pull = 1 / (len/200 + .0001) -- closer particles will be sucked in more quickly
p.vx = p.vx + pull * dx -- vx and vy hold the particles velocity
p.vy = p.vy + pull * dy -- initialize accordingly
p.x = p.x + p.vx * dt
p.y = p.y + p.vy * dt
p.direction=math.atan2(p.vy,p.vx) -- orient in direction of velocity!
end
One way to initialize the velocity could be to set it to a random amount tangent to the orbit of the particle, i.e.:
Code: Select all
for a=1,30 do
local p = {x = math.random(-50,50), y = math.random(-50,50), direction = 0}
local x,y = -p.y, p.x -- tangent vector
local len = math.sqrt(x*x + y*y)
local speed = math.random(20,50)
p.vx = x/len * speed
p.vy = y/len * speed
blackhole[1].particle[a] = p
end