0
votes

I'm trying to make a simple magnet effect when my character is near a coin this should move to his position

I have this:

if(Mycharacter.position.x +2  >= position.x)    //position = coin position
                {

            body.setTransform(Mycharacter.position.x, Mycharacter.position.y, 0);
                 }

This is close to what I want but I need to be able to see the movement of the coin to my character.

I'm still very new to Box2d and Libgdx so if possible keep it really simple guys, it doesn't help I'm terrible on physics. Thanks in advance.

2
Perhaps this was better suited for Game Development?Uwe Allner
This question seems to come up almost every week... this might help: stackoverflow.com/questions/24516945/…iforce2d

2 Answers

2
votes

I found the answer:

if("Any condition")
{
  body.setLinearVelocity((Character.position.x - position.x) * Velocity, (Character.position.y - position.y)* Velocity);
}

Reminder that this is just the simplest way to achieve what I wanted. I'm sure there a more proper ways to do it.

0
votes

You can do this:

1. Compute vector from you to coin (vx = coin.x - player.x, same for y)
2. Compute the vectors's distance (using MathUtils.sqrt(vx*vx+vy*vy))
3. If distance is shorter than magnet range, then reduce the distace.
4. recompute new vector from player to coin (vx *= (newDistance/oldDistance))
5. update coin'S position