How can i know if i have reched to and edge of an object and before that play an animation and if rayCast Is The Soulution How can i use it on the Cube Edge ?
I was hoping someone would give a nice ‘pro’ answer, but this is how I tackled the problem.
- calculate distance between the center of 2 objects
- raycast from each object
- each raycast should hit collider of other object
- raycast distance should be less than center distance, the difference being the distance between the object’s center and the edge of the collider facing the other object
- calculate both colliders’ difference , and subtract them from the center distance
- value should be distance between the colliders.
Create a new scene, attach the below script to the camera or an empty gameObject.
Create 2 cubes, and drag-n-drop them in the script’s Inspector ( obj1 and obj2 ).
Change the scene view to ‘wireframe’ so the debug lines can be seen.
Hit Play and move the cubes around. The GUI shows the difference between the center’s and colliders.
#pragma strict
public var obj1 : Transform;
public var obj2 : Transform;
private var centerDiff : float = 0.0; // difference between the centers
private var colliderDiff : float = 0.0; // difference between the collider edges
private var rayDist1 : float = 0.0;
private var rayDist2 : float = 0.0;
private var drawlineOffset : Vector3 = Vector3(0, 0.02, 0); // for the drawlines to not render over each other
function Update()
{
centerDiff = (obj2.position - obj1.position).magnitude; // distance between 2 objects
var rayHit : RaycastHit;
if (Physics.Raycast( obj1.position, Vector3.zero - (obj1.position - obj2.position).normalized, rayHit) )
{
Debug.DrawLine(obj1.position, rayHit.point, Color.red);
rayDist1 = Vector3.Distance(rayHit.point, obj1.position);
}
if (Physics.Raycast( obj2.position, Vector3.zero - (obj2.position - obj1.position).normalized, rayHit) )
{
Debug.DrawLine(obj2.position + drawlineOffset, rayHit.point + drawlineOffset, Color.green); // offset so line can be seen
rayDist2 = Vector3.Distance(rayHit.point, obj2.position);
}
colliderDiff = centerDiff - ( centerDiff - rayDist1 ) - ( centerDiff - rayDist2 ); // colliderDiff - (collider2 radius) - (collider1 radius)
}
function OnGUI()
{
GUI.Box(Rect(10, 5, 200, 25), "center Difference = " + centerDiff.ToString() );
GUI.Box(Rect(10, 35, 200, 25), "collider Difference = " + colliderDiff.ToString() );
}
[1390-collider+diff.png|1390]