Hullo Unityers,
Simple problem today: how do I go about checking line-of-sight? I really just want to know if there are any colliders between Object A and Object B.
This is of course ridiculously easy, using either Physics.Linecast or Physics.Raycast. However, my problem is if I just do
if (Physics.Linecast(transform.position, target.position))
{
Debug.Log("Line of Sight!")
}
This doesn’t quite work, because it’s hitting the main transform’s collider, and the linecast is stopped right away.
Basically, all I want is a linecast that checks if there’s anything between point A and point B EXCEPT the main object and the target. Is there any way to dynamically add them to layers or anything? You’d think this would be a pretty basic issue, there should be a simple way to check if two objects are obscured.
Thanks for any help guys!
Funny I just did this myself and decided to look in scripting to see if I could help anyone.
Put your main object layer on 8 and put this in the code:
var layerMask = 8;
function Start(){
layerMask = ~layerMask;
}
Edit:
Forgot to say change this too:
var hit : RaycastHit;
if (Physics.Linecast(transform.position, target.position, hit, layerMask))
Not sure if you need the hit var or not.
Thanks very much, works perfectly. Here’s my final line of sight checker…
var layerMask = 1 << layer;
layerMask = ~layerMask;
gameObject.layer = layer;
var hit : RaycastHit;
if (Physics.Linecast(transform.position, target.position, hit, layerMask))
{
if (hit.collider.gameObject.tag == "Player")
{
PlayerDamage(target);
}
}
gameObject.layer = startingLayer;
For anyone that’s interested. Basically just assigns the object to the raycaster layer, ignores that layer and checks if what you’ve hit is the target. Works quite well.