Skip to content

Instantly share code, notes, and snippets.

@James-Frowen
Last active June 26, 2020 21:11
Show Gist options
  • Save James-Frowen/23beb2bbe190868db05d1017c100e580 to your computer and use it in GitHub Desktop.
Save James-Frowen/23beb2bbe190868db05d1017c100e580 to your computer and use it in GitHub Desktop.
Move script for fixed distance moving, Useful when moving between spaces on a grid
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FixedDistanceMove : MonoBehaviour
{
private bool moving = false;
public void StartMove(Vector3 target, float travelTime)
{
if (this.moving || willCollide(target)) { return; }
this.moving = true;
Debug.Log("Start Moving");
StartCoroutine(moveCoroutine(target, travelTime));
}
private bool willCollide(Vector3 target)
{
var origin = this.transform.position;
var direction = (target - origin).normalized;
RaycastHit hit;
if (Physics.Raycast(origin, direction, out hit, Vector3.Distance(origin, target)))
{
Debug.Log("cant move, collision hit with :" + hit.collider.name);
return true;
}
return false;
}
private IEnumerator moveCoroutine(Vector3 target, float travelTime)
{
Vector3 startPos = this.transform.position;
float t = 0;
while (t < 1)
{
this.transform.position = Vector3.Lerp(startPos, target, t);
t += Time.deltaTime / travelTime;
yield return null;
}
this.moving = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment