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:     

2 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

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.