S&box Wiki

Revision Difference

Triggers#563002

<cat>Code.Physics</cat> <title>Triggers</title> ⤶ # What is a trigger⤶ ⤶ When a collider component is marked as a trigger, other physics objects pass right through and can detect when they enter or exit the collider.⤶ ⤶ <upload src="b4aa4/8dd1174da934054.mp4" size="102148" name="sbox-dev_zBUmPyOwxC.mp4" />⤶ # Detecting Triggers To detect when an object enters or exits a trigger, both GameObjects must have a collider component attached, with the `Is Trigger` box checked on the trigger GameObject. ⤶ Then create a component on the `same GameObject` as the collider marked as a trigger, and inherit from `Component, Component.ITriggerListener`⤶ To detect when an object enters or exits another collider, both GameObjects must have a collider component attached(box, sphere, etc), with the `Is Trigger` box checked on one of them. ⤶ For a component to detect triggers, it must be on the `same GameObject` as one of the collider components.⤶ <upload src="b4aa4/8dd117562e0073f.png" size="14607" name="image.png" />⤶ ⤶ First inherit from `Component, Component.ITriggerListener`, then implement `public void OnTriggerEnter()` or `public void OnTriggerExit`, `public void` is necessary. In the parenthesis, add `Collider other` to get the entered / exited collider component or `GameObject other` to get the GameObject it is on.⤶ ```cs ⤶ public sealed class TriggerDebug : Component, Component.ITriggerListener⤶ public sealed class TriggerExample : Component, Component.ITriggerListener, Component.ICollisionListener⤶ { [Property] public NameTagPanel NameTag { get; set; } ⤶ int iTouching; ⤶ void ITriggerListener.OnTriggerEnter( Collider other ) ⤶ // Called when we enter a trigger collider, sets "other" variable to the collider component we entered. public void OnTriggerEnter( Collider other ) { iTouching++; ⤶ NameTag.Name = $"{iTouching} touching\n{other.GameObject.Name} entered";⤶ Log.Info( $"Entered Trigger{other.GameObject.Name}" ); } ⤶ void ITriggerListener.OnTriggerExit( Collider other ) // Called when we exit a trigger collider, sets "other" variable to the gameobject we exited. public void OnTriggerExit( GameObject other )⤶ { iTouching--; ⤶ NameTag.Name = $"{iTouching} touching\n{other.GameObject.Name} left";⤶ Log.Info( $"Left trigger {other.Name} " ); } } } ```⤶ Alternatively, with RigidBody.Touching we can get a list of all colliders intersecting us⤶ ⤶ ```cs⤶ // Gets or creates a RigidBody component on this GameObject⤶ [RequireComponent] private Rigidbody rb { get; set; }⤶ protected override void OnFixedUpdate()⤶ {⤶ // Prints the amount of colliders we are intersecting to the console⤶ Log.Info( rb.Touching.Count() );⤶ }⤶ ``` ⤶ <note>NameTagPanel is a custom razor component that displays text on a **World Panel**</note>⤶ ⤶ <upload src="b4aa4/8dc3b149e74a703.mp4" size="4036001" name="sbox-dev_bMHJ0Vp4ne.mp4" />⤶ <upload src="b4aa4/8dd11772985c5f9.mp4" size="1493000" name="sbox-dev_r2t2mK0s6R.mp4" />⤶