Faults with Grid-Based movement...

I have a few uncertainties here. I basically achieved the basics of moving the object by 1 when one of the directional keys are pressed, and it works fine. However, I also wanted the “Q” (left) and “E” (right) keys to rotate the object 90° to their direction. This is my script, I was unsure how to do the rotation, even after an hour on the Unity Script Reference.

using UnityEngine;
using System.Collections;

public class movement : MonoBehaviour {
	public float speed = 2.0f;
	
	private Vector3 endpos;
	private bool moving = false;
	
	void Start () {
		endpos  = transform.position;
	}
	
	void Update () {
		if (moving && (transform.position == endpos))
			moving = false;
		
		if(!moving && Input.GetKey(KeyCode.W)){
			moving = true;
			endpos = transform.position + Vector3.forward;
		}
		
		if(!moving && Input.GetKey(KeyCode.A)){
			moving = true;
			endpos = transform.position + Vector3.left;
		}
		
		if(!moving && Input.GetKey(KeyCode.S)){
			moving = true;
			endpos = transform.position + Vector3.back;
		}
		
		if(!moving && Input.GetKey(KeyCode.D)){
			moving = true;
			endpos = transform.position + Vector3.right;
		}
		
		if(!moving && Input.GetKey(KeyCode.Q)){
			moving = true;
			endpos = UNSURE WHAT TO PLACE HERE;
		}
		
		if(!moving && Input.GetKey(KeyCode.E)){
			moving = true;
			endpos = UNSURE WHAT TO PLACE HERE;
		}
		
		transform.position = Vector3.MoveTowards(transform.position, endpos, Time.deltaTime * speed);
	}
}

Thanks in advance! :smiley:

transform.rotate(0,90,0);

  • Your test (transform.position == endpos) is dangerous… it works for now, because MoveTowards can hit the target exactly, but be aware that if you use something else later, it could be that you animate the position really close to the target, but never hit it.

  • The speed parameter works to speed things up, but you probably change it in code and it stays the same in the inspector… change it in the inspector

  • to move the way you want, use relative direction, e.g. endpos = transform.position + transform.forward; Watch out, there is no left/back, you need to use -right and -forward

  • for rotating, do something like: transform.Rotate(Vector3.up, 90) and Input.GetKeyDown(KeyCode.E) or you will rotate every 1/60 second