Thanks for the explanation!
Following your suggestion, at the beginnig I was thinking on implementing the code on the coin factory script like:
function on_message(self, message_id, message, sender)
if message_id == hash("magnet_trigger") then
local player_pos = go.get_world_position(self.player_obj_id)
local r = player_pos - go.get_world_position()
local d = vmath.length(r)
self.velocity = self.velocity + vmath.normalize(r) * pow2(1000 / (d + 60)) * self.buff
else...
...
end
function update(self, dt)
self.velocity = self.velocity * (1 / (1 + 0.2*dt))
if vmath.length(self.velocity) > 200 then
self.velocity = vmath.normalize(self.velocity) * 200
end
go.set_position(go.get_position() + self.velocity * dt)
end
But then, if the player jumps or falls after the vector has been set, the coin will end up somewhere else, right?
So I’m thinking that what you said about putting both functionalities in the update function would be better, so the coin can follow the player wherever he/she moves, like:
function on_message(self, message_id, message, sender)
if message_id == hash("magnet_trigger") then
self.follow_player = true
else...
...
end
function update(self, dt)
...
if self.follow_player then
-- get player position every loop, so we can follow him/her ;P
local player_pos = go.get_world_position(self.player_obj_id)
-- get direction of attraction and multiply by calculated power of attraction
local r = player_pos - go.get_world_position()
local d = vmath.length(r) -- distance in pixels between coin and player??
-- (Here I don't know if I am performing twice the same operation
-- or if I can get rid of one of the following lines...)
self.velocity = self.velocity + vmath.normalize(r) * pow2(1000 / (d + 60)) * self.buff
self.velocity = self.velocity * (1 / (1 + 0.2*dt))
-- limit top speed of attracted item to 200 pixels/sec.
if vmath.length(self.velocity) > 200 then
self.velocity = vmath.normalize(self.velocity) * 200
end
-- apply vector and fly towards player
go.set_position(go.get_position() + self.velocity * dt)
end
end
I’ll try this as soon as I get to my computer