Magnet/Item tracking Question

Hello,

I am trying to build a magnet/object position following effect in my app. When an object is spawned, it checks to see if the magnet feature is enabled and if so, shoots toward the magnetized object. The problem is if the magnetized object changes position, the spawned object doesn’t adjust it’s position to match the new position of the magnetized object.

I’ve tried many methods to try to get this to work and have come up empty. Does anyone have any ideas?

Any help is much appreciated
Thank you in advance [import]uid: 47722 topic_id: 26851 reply_id: 326851[/import]

Hello!

Here’s simple following function where you can make one object follow another even with the distance changing. In this case an enemy is following a ship (can be anything you want though)

Hope it’s what you need

[code]

local function follow()
local angle = math.atan2(Ship.y - enemy.y, Ship.x - enemy.x)
enemy.x = enemy.x + (math.cos(angle) * 2) --speed x axis
enemy.y = enemy.y + (math.sin(angle) * 2) --speed y axis
end
Runtime:addEventListener(“enterFrame”, follow)

–This may be easier to change the speed
local speed = 2

local function follow()
local angle = math.atan2(Ship.y - enemy.y, Ship.x - enemy.x)
enemy.x = enemy.x + (math.cos(angle) * speed)
enemy.y = enemy.y + (math.sin(angle) * speed)
end
Runtime:addEventListener(“enterFrame”, follow)

[import]uid: 113909 topic_id: 26851 reply_id: 108987[/import]

If you’re using the physics engine, you can also join the 2 objects with a “touch” joint and then start a Runtime listener that updates the “target” of the touch joint to the magnet. This will result in the object constantly tracking/following the magnet no matter where the magnet moves. You can additionally adjust the simulated power/pull of the magnet by tweaking the parameters of the joint.

Basically, I’m a proponent of using the physics engine for advanced game aspects IF you’re already using it for basic physics. I’m not suggesting you implement physics for the sole purpose of a magnet effect, but if you already have the engine/library included, it makes sense to use it for this.

The other suggested solution is fine too, of course. Up to you which method you prefer. :slight_smile:

Brent Sorrentino
Ignis Design [import]uid: 9747 topic_id: 26851 reply_id: 108993[/import]

Thank you for the quick replies. I ended up going with the first solution and it works very well (everything I was looking for). I will keep the second solution in mind for future projects. I really appreciate the help.

Thanks again [import]uid: 47722 topic_id: 26851 reply_id: 109074[/import]

Well thanks for using my method :slight_smile: it worked great for me as well.
happy coding,
-Boxie
[import]uid: 113909 topic_id: 26851 reply_id: 109232[/import]