Last active
December 10, 2015 22:58
-
-
Save mzugn/4505853 to your computer and use it in GitHub Desktop.
Move on a grid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* RectangularMover.cs | |
* Purpose: Moves the object to the position where mouse-click points | |
* on a *rectangular* path. First on X, then on Z axis. | |
* Additional movement can not be issued until the current one finishes. | |
* Uses coroutines for niceties. | |
* Author: z_murc @ UnityAnswers | |
*/ | |
using UnityEngine; | |
using System.Collections; | |
public class RectangularMover : MonoBehaviour { | |
public float moveSpeed = 10f; | |
Transform _transform; | |
bool movementInProgress = false; | |
float distanceThreshold = 0.01f; | |
void Awake() | |
{ | |
_transform = GetComponent<Transform>(); | |
} | |
void Update () | |
{ | |
if (Input.GetMouseButtonDown(0) && !movementInProgress) | |
{ | |
RaycastHit hit; | |
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); | |
if(Physics.Raycast(ray, out hit, Mathf.Infinity)) | |
{ | |
if (hit.collider.tag == "Floor") | |
{ | |
StartCoroutine(RectMove(hit.point)); | |
} | |
} | |
} | |
} | |
IEnumerator RectMove(Vector3 destination) | |
{ | |
// this will be true in the following Updates, until this whole coroutine finishes | |
movementInProgress = true; | |
// 0. the movement vector | |
Vector3 moveVector = destination - _transform.position; | |
Vector3 target; | |
// 1. move on X | |
target = _transform.position + new Vector3(moveVector.x, 0, 0); | |
yield return StartCoroutine(MoveTo(target)); | |
// 2. when finished, move on Z | |
target = _transform.position + new Vector3(0, 0, moveVector.z); | |
yield return StartCoroutine(MoveTo(target)); | |
movementInProgress = false; | |
} | |
IEnumerator MoveTo(Vector3 destination) | |
{ | |
while (true) | |
{ | |
_transform.position = Vector3.MoveTowards(_transform.position, destination, | |
moveSpeed * Time.deltaTime); | |
if (Vector3.Distance(_transform.position, destination) < distanceThreshold) | |
yield break; | |
else | |
yield return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment