Distance between objects

Hi!
I got player and few coins in my platformer game which I can collect. I want the player to attract those coins when the player is close enough. Have you any idea how to achieve this?

Currently I add coins to group and coins came from Coin class that is extended by Phaser.GameObjects.Image

*At the same time I want coin body size to be the same as coin texture size
** Using Arcade Physics

You can use 1 larger physics body around every coin that activates attracting and a smaller one around that collects it.

You can use Phaser.Math.Distance.Between between the player and all the coins on every frame but that’s not very efficient for more coins.

Or combining both by having only the larger body that activates the distance checking without the smaller one and collecting the coin manually when the distance is low enough.

First one is the simplest.

1 Like

Thanks for answer!

You can use 1 larger physics body around every coin that activates attracting and a smaller one around that collects it.

That what i was thinking of but I know that with matterjs I can use sensor and compound body, how to achieve same effect with arcade physics?

That I can’t tell you. I’ve only ever used Matter in P3.

Calculating the distance manually is actually likely to be more efficient, especially if you use Phaser.Math.Distance.Squared instead of Between. Physics bodies have to be synced with their Game Objects, moved, and checked for collision every frame, which is more expensive (in terms of memory and almost certainly in terms of performance) than a single loop which does a simple calculation.

As for the simplicity of either method, it depends on the physics engine. I can’t say anything about Matter because I haven’t used it, but you’d have to sync the two bodies manually using another Game Object with Arcade Physics. There are no compound bodies, each body must have a Game Object (this requirement no longer exists in Arcade Physics 2, but that version is not stable yet), and each Game Object can only have one body.

2 Likes

Yes, that is the best solution, I think. I am calculating the distance between coins and player in update loop in Coin class. Thanks!