Hey I’m relatively new using unity and I want to create a top down grid based movement system.
The player can move around my level perfectly fine, I just want the player to move to each new vector over a short amount of time, so it’s not instantly teleporting a spot to the right for example.
How can I achieve this easily?
This is the code I’m using currently:
public Rigidbody2D rb;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown(KeyCode.D) == true)
{
if (UpDownLeftRight.canMoveRight == true)
{
transform.Translate(new Vector2(1.12f, 0), Space.World);
}
}
if (Input.GetKeyDown(KeyCode.A) == true)
{
if (UpDownLeftRight.canMoveLeft == true)
{
transform.Translate(new Vector2(-1.12f, 0), Space.World);
}
}
if (Input.GetKeyDown(KeyCode.W) == true)
{
if (UpDownLeftRight.canMoveUp == true)
{
transform.Translate(new Vector2(0, 1.12f), Space.World);
}
}
if (Input.GetKeyDown(KeyCode.S) == true)
{
if (UpDownLeftRight.canMoveDown == true)
{
transform.Translate(new Vector2(0, -1.12f), Space.World);
}
}
}
}
Please use code blocks for code snippets. It’s that “Code: <>” . Makes your code much more readable. And this post probably would be better in another forum area than 2D, maybe scripting?
You need to perform the move during many frames. If you use Translate that way, you move the GameObject in an instant.
To move object slowly over time, you need to use deltaTime:
Above code would move your character 1 unit in a second.
But that won’t solve your problem completely.
As you want a grid based system, you need to make that character perform the move completely, then accept a new move based on the player input. So, you could set up a simple movement system, by using a boolean to check if you are moving.
if (isMoving == true) {
// Don't accept new input.
}
You could use a coroutine that starts when a move can be triggered:
if (isMoving == false) {
StartCoroutine(MoveToSomePosition(startPos, endPos, movementTime);
}
You could cannibalize code from this Unity Answers posting for the actual movement routine:
This way you can make your character move from position A to B, and the player can’t intervene by pressing wrong keys, if that’s what you want.