Last active
November 16, 2017 02:28
-
-
Save m0o0scar/372bfc99a59350dce4979330280f91f5 to your computer and use it in GitHub Desktop.
Simple way to calculate closest distance to a cube surface
This file contains hidden or 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
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