C# script to controll player character or object movement in tile based games.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// © 2017 TheFlyingKeyboard
// theflyingkeyboard.net

public class TileMovementController : MonoBehaviour {
    [SerializeField] private float distanceToMove;
    [SerializeField] private float moveSpeed;

    private bool moveToPoint = false;
    private Vector3 endPosition;

  void Start () {
        endPosition = transform.position;
    }
  
  void FixedUpdate () {
        if (moveToPoint)
        {
            transform.position = Vector3.MoveTowards(transform.position, endPosition, moveSpeed * Time.deltaTime);
        }
  }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A)) //Left
        {
            endPosition = new Vector3(endPosition.x - distanceToMove, endPosition.y, endPosition.z);
            moveToPoint = true;
        }

        if (Input.GetKeyDown(KeyCode.D)) //Right
        {
            endPosition = new Vector3(endPosition.x + distanceToMove, endPosition.y, endPosition.z);
            moveToPoint = true;
        }

        if (Input.GetKeyDown(KeyCode.W)) //Up
        {
            endPosition = new Vector3(endPosition.x, endPosition.y + distanceToMove, endPosition.z);
            moveToPoint = true;
        }

        if (Input.GetKeyDown(KeyCode.S)) //Down
        {
            endPosition = new Vector3(endPosition.x, endPosition.y - distanceToMove, endPosition.z);
            moveToPoint = true;
        }
    }
}

 

Unity C# 2D Tile Movement
Tagged on:     

4 thoughts on “Unity C# 2D Tile Movement

  • July 20, 2017 at 10:45 am
    Permalink

    Is there any other reason why the two fields, distanceToMove and moveSpeed, are both serialized other than to make them appear on the editor while hiding them to other classes?

    Thanks!

    Reply
    • July 20, 2017 at 4:36 pm
      Permalink

      No, they are both used exacltly as you say 🙂

      Reply
      • November 20, 2017 at 11:00 am
        Permalink

        Is it possible to play an animation per tile the ‘player’ is moving? As you see in pokemon, the player moves one tile, animation shows player stepping with the right foot, then one more tile and the player steps with the other foot and so on. I’ve been dying while trying to find out how this works with the animation.

        Reply
        • November 20, 2017 at 12:14 pm
          Permalink

          Yes, it’s possible, I’ve done that in Catacombs Of The Squid: https://theflyingkeyboard.itch.io/catacombs
          Just make animation of walk and idle, and make bools or triggers. When player starts walking change that variable, if you make the animation speed good enough it will seam smooth and natural, hope it helps 🙂

          Reply

Leave a Reply

Your email address will not be published. Required fields are marked *