7
\$\begingroup\$

I'm making a top-down-2D game. When my player moves, the cursor does not move with it. In my game, the player moves by facing the cursor and then walking toward it. This means that eventually, the player will reach the cursor and then glitch out.

How do I handle player movement when they reach the mouse?

\$\endgroup\$
  • 2
    \$\begingroup\$ A few illustrations or screenshots will help make it more clear what you're trying to do/fix. \$\endgroup\$ – William Mariager Dec 23 '14 at 11:00
  • 1
    \$\begingroup\$ You'll have to handle this case one way or another (e.g. how about only moving if there's some minimum distance?). Most games I can think of will either ignore a cursor that's too close or just continue turning you in the direction it's facing. \$\endgroup\$ – Mario Dec 23 '14 at 13:08
  • \$\begingroup\$ If there's some specific problem arising you're trying to solve, add some more information (source code!). Right now it's not really clear what you're looking for other than a "yes" or "no" (unlikely). \$\endgroup\$ – Mario Dec 23 '14 at 13:09
15
\$\begingroup\$

Many top down 2D games have the camera centered on the player. This makes the mouse always 'move away' from the player. The 'glitch out' you mention can be handled by adding a dead zone immediately around the player. If the mouse is clicked within this deadzone, the move and rotate commands are not activated.

The move and rotate behavior is not intended to operate under such short distances. It'll often overshoot the target and this is where the 'glitch' is introduced. The algorithm essentially oscillates on the target never being able to reach it. The alternative to fixing this is to have some kind of maximum velocity based on distance to the target. Take a look at steering arrival behaviors to learn more about this problem:

Avoiding orbiting in pursuit steering behavior

Arrive steering behavior

| improve this answer | |
\$\endgroup\$
  • 2
    \$\begingroup\$ +1 for the dead zone, this is probably the fastest and simplest way to fix the problem. \$\endgroup\$ – Alexandre Desbiens Dec 23 '14 at 16:49
  • 1
    \$\begingroup\$ Interesting. In all my games if distance<speed I alter speed to equal distance, move one tick, then stop the animation. \$\endgroup\$ – Mooing Duck Dec 23 '14 at 17:37
  • \$\begingroup\$ +1 indeed, a simple "if cursor > minDistance from player, then move" tends to work nicely, and you can drastically alter the control and how your game plays by toying with the number. A small one avoids glitches, while a large one changes the fundamental handling so it's more loose and forgiving if tiny hand-jerks. \$\endgroup\$ – BrianH Dec 23 '14 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.