In a previous post I talked about creating wires (using Bézier curve) using LineRenderer. I am using a PolygonCollider2D to wrap the wire (see below):
GameObject wire = new GameObject ();
LineRenderer lineRenderer = wire.AddComponent<LineRenderer> ();
PolygonCollider2D wireCollider = wire.AddComponent<PolygonCollider2D> ();
After drawing the curve and attaching the collider (as described in previous post), I added a new component to my gameObject (a WireController):
WireController wireController = wire.AddComponent<WireController> ();
The WireController currently has only one method:
void OnTriggerEnter2D(Collider2D other) {
Debug.Log ("I'm hit!");
}
I use a Physics2D.Raycast to check if my mouse pointer is at any point interacting with the wire:
void CastRay() {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, 100);
if (hit) {
Debug.Log (hit.collider.gameObject.name);
}
}
If I call CastRay() inside a Update() loop, if (hit)
returns true (if the mouse pointer is over the gameObject, in this case, the wire), but the OnTriggerEnter2D
method never gets called.
A few observations:
collider.isTrigger = true;
- The
WireController
is attached to the newly created gameObject (it's visible in the Unity editor at runtime)
Any help is much appreciated!
OnTriggerEnter
event, because it's when aCollider
enters it. ARaycast
doesn't have a proper collider, it's different mechanics. \$\endgroup\$