- Home /
raycastHit.point - How do I make it ignore colliders?
Hello, I'm using raycasts to determine a field on my grid-based map, but problems occur when I place other objects on the field.
int fieldLayerMask = 1 << 9;
private Vector3Int gamePosition;
private Vector3 scenePosition;
private Ray ray;
private RaycastHit hit;
private void GetPositionOnMap()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, fieldLayerMask))
{
//Debug.Log("Hit GameObject: " + hit.transform.gameObject.name);
scenePosition = hit.point;
gamePosition = new Vector3Int(Mathf.FloorToInt(hit.point.x / tile_size), Mathf.FloorToInt(hit.point.y / tile_size), Mathf.FloorToInt(hit.point.z / tile_size));
Debug.Log("gamePosition: " + gamePosition + "; scenePosition: " + scenePosition + "; hit.point: " + hit.point);
}
}
Despite the fact I'm using a layer mask hit.point returns coordinates on objects that are sitting on top of my field if their (box) collider is active. Even though they're not part of layer 9.
Does anyone know why that is and what I can do to fix this? I'd rather keep the collider of those objects active since I want to raycast them with other functions. Just not with this one.
Answer by LCStark · Sep 30, 2018 at 05:47 PM
Your fieldLayerMask
isn't actually used. Physics.Raycast
does not have a three-parameter version that matches your arguments. Instead, your layer mask is being recasted to act like the maximum distance, to match this version:
public static bool Raycast(Ray ray, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
Try adding the proper third parameter:
Physics.Raycast(ray, out hit, Mathf.Infinity, fieldLayerMask)
Thank you very much. This works. I just saw int layer$$anonymous$$ask as the third parameter and didn't realize the second parameter wasn't the out parameter.