In my 2D game I have the hero and coins that appear randomly. When the hero gets a power-up, his velocity increases so he flys faster. Power-up is active for 10 seconds. When the powerup is active, if he is close to coins, coins should follow and collide with him like in Temple Run. I am not using any box2d type physics. For collision, I am using rectangular intersection checks and collision is not the problem here.
How do I achieve this effect of coins to follow the hero like magnets?
My current implementation is – check the distance between each coin in the coin group and the hero. If the target distance for coin movement is satisfied, change the coin’s velocity on x based the on the velocity of the hero but this is not working as expected. How do I apply the impulse?
Change it to work on the inverse of the distance. For reference, Newton’s (mostly correct) law of Universal Gravitation:
Where
Fis the force,Gis some constant,ris the radius (the seperation distance),m1is the mass of the coin, andm2is the mass of the hero.We also know Newton’s Second Law of Motion:
Where
Fis the force,mis the mass of the coin, andais the acceleration of the coin.We can combine those two equasions to get:
From there, we know that the hero’s “mass” is going to be proportional to the hero’s area (2D objects don’t really have mass but let’s just pretend for a second), in other words:
Assuming you’re scaling your hero equally in all directions, this means that the “mass” of your hero will be proportional to the square of the size scale factor
S, like so:This all boils down to:
Where
ais the acceleration (the quantity you’re looking for),Sis the scale factor of the hero size,dis the distance from the hero to a coin, andkis a constant factor (just fudge it until coins move the right speed).