Malakai
Malakai

Reputation: 81

Moving objects to another object with delay

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?

Upvotes: 1

Views: 538

Answers (1)

Wug
Wug

Reputation: 13196

Change it to work on the inverse of the distance. For reference, Newton's (mostly correct) law of Universal Gravitation:

Where F is the force, G is some constant, r is the radius (the seperation distance), m1 is the mass of the coin, and m2 is the mass of the hero.

We also know Newton's Second Law of Motion:

Where F is the force, m is the mass of the coin, and a is 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 a is the acceleration (the quantity you're looking for), S is the scale factor of the hero size, d is the distance from the hero to a coin, and k is a constant factor (just fudge it until coins move the right speed).

Upvotes: 3

Related Questions