@Crumble - rather than moving 1/20 of the difference each time (which means you’ll never reach the destination, I suggest you move at a constant speed (maybe different for each ball).
So suppose you set the speed like this when you spawn
--set speed as a random fraction between 2 and 4
--see note underneath about spawnLoc
table.insert(ellipses,{
loc=vec2(spawnLoc[random].x,spawnLoc[random].y),
speed=math.random()*2+2
})
then in draw
for a,b in ipairs(ellipses) do
local d=b.loc:dist(vec2(x,y)) --calculate distance to (x,y)
if d>0 then --apply speed limit,
d=math.min(1,b.speed/d) --calc fraction of distance to move
b.loc.x=b.loc.x+(x-b.loc.x)*d
b.loc.y=b.loc.y+(y-b.loc.y)*d
end
sprite(ball,b.loc.x,b.loc.y,64,64)
end
First, you should not set the random location to spawnLoc[random], because you may think you are making a new copy of spawnLoc[random], but what you are actually doing is pointing at the original item. Then, when you change your ball’s position, it will change the x,y position of the spawnLoc item you started with.
I think of it as though Codea variables have small pockets that can only fit a string or a number. So if you say b=a
, when a is a string or number, then you will be making a new copy of a, and if you change b afterwards, a will not change.
But if a is anything but a string or number, such as a table, a vec2 etc, then when you say b=a
, what gets put in b is the memory address of a, not a copy of a, and if you change b, you will also change a, because they are the same thing. So you’ll see I have copied the x and y values from spawnLoc separately, and because they are just numbers, they will be copied, so changes to our ball position won’t affect the original spawnLoc values.
Second, if you want the balls to move at constant speed, calculate the distance to the target, divide it by the speed of the ball (with maximum of 1), to get the fraction of the distance that can be moved. Apply this fraction to the x and y differences.