darknath
darknath

Reputation: 25

Unity - Laser activated objects using raycast

I am trying to recreate a simple laser puzzle mechanic like seen in The Talos Principle - where i have a laser emitter that i can move and rotate, and when the beam (raycast and LineRenderer) hits a specific object, that object will become "active". However when the object is no longer being hit by a laser it should "deactivate".

I am having troubles with the Deactivate part. Is there a way to tell the object that it is no longer being hit by a raycast, or add a collider to the LineRenderer maybe? Or some third way to tell the object that it is no longer being hit by any lasers.

Upvotes: 2

Views: 566

Answers (2)

Doh09
Doh09

Reputation: 2385

When your target is hit by a raycast, you could use the RaycastHit reference to acquire a script and update the cooldown.

Lets say we have RaySender and RayReceiver.

RaySenderScript

public class RaySenderScript{
    RaycastHit Hit;
    void FixedUpdate(){
        //SendRaycast and store in 'Hit'.
        if (Hit.collider != null)
           { //If raycast hit a collider, attempt to acquire its receiver script.
               RayReceiverScript = Hit.collider.gameObject.GetComponent<RayReceiverScript>();
               if (RayReceiverScript != null)
                  { //if receiver script acquired, hit it.
                      RayReceiverScript.HitWithRay();
                  }
           }
    }  
}

RayReceiverScript

public class RayReceiverScript{
    public float HitByRayRefreshTime = 1f;
    float RayRunsOutTime;
    public bool IsHitByRay = false;
    void Start()
    {   //Initialize run out time.
        RayRunsOut = Time.time;
    }

    void Update()
    {
        if (Time.time > RayRunsOutTime)
        { //check if time run out, if it has, no longer being hit by ray.
            IsHitByRay = false;
        }
    }

    public void HitWithRay(){ //method activated by ray sender when hitting this target.
         IsHitByRay = true;
         RayRunsOutTime = Time.time + HitByRayRefreshTime;
    }  
}
  1. Sender strikes Receiver with a ray.
  2. Sender has a reference to Receiver, it uses GetComponent() to access it. It can then say receiverScript.HitWithRay();
  3. Receiver keeps checking if it no longer is receiving, if it isnt, it stops being hit by ray.

Upvotes: 1

Orifjon
Orifjon

Reputation: 1097

Add all objects hit by laser to collection and check if current target is in this collection. If it is not there, then it is "deactivated".

Upvotes: 0

Related Questions