- Home /
LayerMask, DrawRay and DrawLine acting weird...
Ok, so I am getting some odd results when I use Physics.DrawRay().
I have created a function for detecting collisions with other game objects on Layer 10.
Unfortunately, while the ray passes through the object, it doesn't record a collision. (Yes I am certain the object has a Mesh Collider on the appropriate layer).
However, if I then use my LayerMask, none of the collisions happen, and it tells me the length must be greater than 0. (I am trying to ignore Layer 0).
In the image below, Red rays indicate no hit, Yellow means the collider is not hitting the appropriate object, and green means it is correct.
Here is a code snippet:
GameObject MakeRayCasters(Vector3[] corners){
GameObject origin = new GameObject("RayCaster");
Vector3 average = new Vector3();
for (int i = 0; i < corners.Length; i++) {
average += corners[i];
}
average /= corners.Length;
RaycastHit hit;
Vector3 PlanarUp = Vector3.Cross((Vector3.zero - northPoints[1]).normalized,(Vector3.zero - northPoints[0]).normalized);
LayerMask ignoreLayer = new LayerMask();
ignoreLayer.value = 0;
origin.transform.position = average;
origin.transform.localRotation = Quaternion.LookRotation((Vector3.zero - origin.transform.position).normalized,PlanarUp);
if (Physics.Raycast(origin.transform.position+(origin.transform.up*50),-origin.transform.up*50, out hit)) {
if (hit.collider.gameObject.layer==10) {
Debug.Log(hit.collider.gameObject.name);
Debug.DrawRay(origin.transform.position+(origin.transform.up*50),-origin.transform.up*50,Color.green,Mathf.Infinity);
} else {
Debug.Log("INVALID HIT: " + hit.collider.gameObject.name);
Debug.DrawRay(origin.transform.position+(origin.transform.up*50),-origin.transform.up*50,Color.yellow,Mathf.Infinity);
}
} else {
Debug.DrawRay(origin.transform.position+(origin.transform.up*50),-origin.transform.up*50,Color.red,Mathf.Infinity);
Debug.Log("MISS: " + hit.point);
}
RayCasters.Add(origin);
return origin;
}
Here is a screenshot:
After further testing, it either has something to do with the angle, or the objects are not being rendered yet...
Which seems a little confusing... I have not setup any coroutines, so why would some objects not be rendered yet?
The invalid hits are registering prematurely on other objects, that are not Instantiated until after the ground has been fully constructed. The Rays are cast before they are even Instantiated...
Answer by Cyber_Defect · Apr 28, 2013 at 05:43 PM
I think I figured out my problem, logic error. I am calling the ray as I build each floor. I need to call it after I build ALL floors :(