Moving the player tile by tile smoothly in Unity

14,172

Solution 1

Here's what I would do: you give your player class a target field, e.g. a 2d vector. This will either contain the current position of the player (when initializing or when the target has been reached) or the target that you want to move the player to.

Now in your update you do this:

if target equals your current position then check user input for movement.
    if user requests movement set target to position adjacent to current position.
else slowly move player towards target.

You may want to create a field for the current position of the player besides the normal position in GameObject. You could then update GameObject.position in the update-cylce by a small delta until the positions of GameObject.position and target have the (roughly! use epsilon when comparing) same value.

Some hints

  • Vector2.MoveTowards can help you
  • To check if the target and position are "close enough" you could subtract one from the other and look at the resulting vector's magnitude.
  • Beware of overshooting when you move towards the target. If your movement distance is more then or equal to the distance between position and target, just set the position to the target.

Solution 2

You could take a look at GridMove which is from UnifyWiki.

You would probably get more of a response if you posted this question to answers.unity3d.com or forum.unity3d.com as these forums are specifically target towards Unity3d.

Share:
14,172
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I want to make the player move by a specific amount (1 tile/unit in this case) and then stop him. Just like in this video:

    http://www.youtube.com/watch?v=DotOAbNngc4

    By pressing a key the player should move smoothly to the next tile, than stops and so on.

    How can I archieve this? (in C#)

  • Admin
    Admin almost 10 years
    Thanks for your help, but could you please give me a little code example for this? I'm a beginner right now and a little overchallenged by that.
  • Mene
    Mene almost 10 years
    I added some hints for you. Asking for a complete code-example is a bit much. If you have no programming experience this is actually quite a complicated task, as there are some pit-falls. I hope my tips will help you. Other than that: Pen and paper are your friends, it may help to visualize a bit. If you have more concrete questions don't hesitate to ask ;D