Working on an explosion script and having difficulties making it work as expected. My debug line draws lines to all the hit objects but my raycast in the same directions returns… nothing. Why? Thanks!
public void Explode()
{
Collider[] hits = Physics.OverlapSphere(transform.position,2);
int i=0;
while(i < hits.Length)
{
RaycastHit rayHit;
Physics.Raycast(transform.position, hits[i].transform.position, out rayHit);
Debug.Log (rayHit.transform); // THIS RETURN NULL!!!!!!!!!!!
Debug.DrawLine(transform.position, hits[i].transform.position,Color.green,10);
i++;
}
if(i>=hits.Length)Destroy(this);
}
edit: I forgot to subtract the origin.position from the target.position to get the direction. Duh.
I don’t think your using the Physics.Raycast correctly. Go and look at the documentation for it. →
function Raycast (origin : Vector3, direction : Vector3, distance : float = Mathf.Infinity, layerMask : int = kDefaultRaycastLayers) : boolean
So it wants the origin of where it starts, the direction, The distance which is optional and any layer which is optional. It also is a boolean function. So you can simply wrap it in a if(Physics.Raycast(myOrigin, myOrgin.transform.forward, 10)
Sorry for the delay was at work. Here’s an Explanation and my solution:
public void Explode()
{
Collider[] hits = Physics.OverlapSphere(transform.position,2);
int i=0;
while(i < hits.Length)
{
RaycastHit rayHit;
//Your current
//transform.position : The Object the component is currently on.
//hits[i].transform.position : An Object that was dectected with your overlapSphere.. This should be a direction.
// If you want it to point back to the the current location you can get the direction
// by Using this formula: Vector3(to - from).normalized;
// So in your case it would be: new Vector3(transform.position - hits[i].transform.position).normalized
//Physics.Raycast(transform.position, hits[i].transform.position, out rayHit);
//So what your really wanting is..
if(Physics.Raycast(transform.position, new Vector3(transform.position - hits[i].transform.position).normalized, out rayHit)
{
Debug.Log (rayHit.transform); // This shouldn't return null.
}
Debug.DrawLine(transform.position, hits[i].transform.position,Color.green,10);
i++;
}
if(i>=hits.Length)Destroy(this);
}