- Home /
Direction/Hit Detection without triggers.
I have 2 objects, neither one can have solid colliders on them, nor do I have any reason to put rigidbodies on them. (Yes I know I can and mark them Kinematic, but that seems like a waste. My issue is that I have one of the objects pointing at the other. When object A is pointing at object B it tells object B it's doing so. But I also need to know when it stops pointing at the object also. A raycast would work but I have no way of A telling B it left or B knowing A left. Also distance matters, it could be from 1-30 m away at any point. My original idea was just to put a trigger on both and put a kinematic RB on A or vise versa but it seems like a waste.
Any opinions/options anyone can think of?
Answer by Bunny83 · Jul 18, 2019 at 01:22 PM
Your wording is a bit confusing but I guess all you want to do is inform A / B that A is no longer pointing at B? If that's the case that can be done easily with a single variable. Lets assume object A has a script A which does perform the raycast- Object B has a script B attached that has a method / methods which should be called by A. Just do this:
public class A : MonoBehaviour
{
float dist = 30;
B obj = null;
void Update()
{
RaycastHit hit;
B hitObj = null;
if (Physics.Raycast(transform.position, transform.forward, out hit, dist))
{
hitObj = hit.transform.GetComponent<B>();
}
// new object was hit
if (hitObj != null && obj == null)
{
obj = hitObj;
obj.A_Starts_Looking_At_B();
}
// previously looked at obj but stopped now
else if(hitObj == null && obj != null)
{
obj.A_No_Longer_Looks_At_B();
obj = null;
}
// looked at another object with a B script
else if(hitObj != null && obj != hitObj)
{
obj.A_No_Longer_Looks_At_B();
obj = hitObj;
obj.A_Starts_Looking_At_B();
}
else
{
// either not looking at B or still looking at the same obj
}
}
}
The method "A_Starts_Looking_At_B()" will be called once when A starts looking at object B. The method "A_No_Longer_Looks_At_B()" will be called once the moment A doesn't look at B anymore. This does support several objects with B scripts.