C# script to controll player character or object movement in tile based games.
using System.Collections; using System.Collections.Generic; using UnityEngine; // ? 2017 TheFlyingKeyboard and released under MIT License // 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
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!
No, they are both used exacltly as you say 🙂
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.
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 🙂
Hi, thanks for the tutorial, one question, if i want to prevent the player move to some places, how do you recommend to do this? I saw a few tutorials that use a Raycast2d but i think is a lot of work for only block the movement, what do you think?
Thanks again!
Hello all,
how can you move like in the catacombs game?
at this code that you mentioned befor, when i push the button, chracter will move and stop.
i just want to hold to the arrow key to keep chracter moving instead of pushing buttons.
when i stop holding the button, jut wnat to chracter stop moving