Skip to content

Instantly share code, notes, and snippets.

@m0o0scar
Last active November 16, 2017 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m0o0scar/372bfc99a59350dce4979330280f91f5 to your computer and use it in GitHub Desktop.
Save m0o0scar/372bfc99a59350dce4979330280f91f5 to your computer and use it in GitHub Desktop.
Simple way to calculate closest distance to a cube surface
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DistanceCalculator : MonoBehaviour {
public GameObject[] targets;
void Update () {
foreach(GameObject target in targets) {
Collider collider = target.GetComponent<Collider>();
if(collider is BoxCollider) {
Vector3 vector = target.transform.position - transform.position;
Ray ray = new Ray(transform.position, vector);
Debug.DrawRay(transform.position, vector, Color.yellow);
RaycastHit hit;
collider.Raycast(ray, out hit, vector.magnitude);
Vector3 projection = Vector3.Project(hit.point - transform.position, hit.normal);
Debug.DrawRay(transform.position, projection, Color.white);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment