Mouse movement on grid

Hey, I can’t figure this out on my own, so I thought I might ask for some help. I’m having a problem with my Mouse movement. My character walks where I want it to, but I want to make it move in a grid, with ‘Move Points’. I already have a script which casts a ray from the mouse position and detects collision, but now i want to make my character move over a grid.
My script:
using UnityEngine;
using System.Collections;

public class MovementScript : MonoBehaviour {

	public bool isCollider = false;
	Vector3 movePosition;
	public float speed = 10F; 
	public Transform player; //The Player
	private float startTime;
	public float duration = 1.0F;
	public int gridSize = 1; //The size of one grid/tile

	void Update () {
         //The mouse click 'n walk part
	     RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
       	if(Physics.Raycast(ray, out hit, Mathf.Infinity))
       	{
         	if(Input.GetMouseButtonDown (0))
         	{
          	     movePosition = new Vector3(hit.point.x,   
                     1.360456F, hit.point.z);
          Debug.Log (hit.collider.name + " " + hit.point);
                  if (hit.collider.name != ("Tile(Clone)"))
	              {
              		isCollider = false;
		      }
          	      else if (hit.collider.name == ("Tile(Clone)"))
		      {
              	   isCollider = true;    
		      }
		      if (hit.collider.tag == ("Player"))
		      {
			   Debug.Log("Player");	
		      }
         	}
       }
       if (isCollider == true)
       {
         	//Here the script for the actual movement
       }	
	}
}

There might have to be a few changes in the ‘movePosition = new Vector3… etc.’ In the game i’m making the player has to walk horizontal and vertical, not diagonal. I really hope someone might be able to help me.

Thanks in advance! :slight_smile:

If you want the character to move like that, you can realize that the vector that represents the movement (change of position) of the character is given like this:

moveVector = hit.point - transform.position;

Of course if you add this to transform.position, it’s gonna be hit.point, effectively replacing the character. But you can also see that moveVector is a vector that’s the sum of the vectors where each one has value for just one of the axes. It’s like when you have a vector in a coordinate system (4,6), that is the same as (4,0) + (0, 6).

So what you do here is calculate moveVector, then in your movement code you go first on the X and then on Z (or the opposite), so you first get to the location transform.position + new Vector3(moveVector.x, 0, 0), then you go to transform.position + new Vector3(0, 0, moveVector.z), and you’re there.

EDIT: I wrote a script which implements this principle with coroutines to keep the code nice and simple:
RectangularMover.cs

alt text