- Home /
OnTriggerEnter for moving object
I've attached an OnTriggerEnter event to my bullets, trying to get the bullet to destroy itself when it encounters an object. But it doesn't seem to work on static objects like walls.
I could use OnCollisionEnter but that's considerably more processor heavy and I don't need any collision information…
I could add an OnTriggerEnter script to all objects in the scene, but also seems wasteful…
Does your "bullet" game object also have a RigidBody associated with it?
I'm not an expert, but a trigger will only be enacted when it hits a trigger, so if you're going to do this, then the objects must be triggers as well. You don't have to add a script though, just simply tag them as something, label them as trigger, then have the bullets get destroyed when they hit that tag. But doing this could make your character not collide, so your best bet would be to have it do a normal collision i believe.
I'm pretty new here ... but one thought ... it might be that a trigger is initiated when something "enters" the trigger collider and not when your dynamic object enters another trigger space.
I believe you're both right. I'll take Bérenger's approach
Answer by Berenger · May 06, 2012 at 05:58 AM
You should cast a ray when the bullet is shot to find it's end point. Once reached, it's destroyed. The speed of a bullet make it inapropriate for colliders, as it travels several times its size in one frame.
On second thoughts, I don't understand how this can work… What if an enemy moves in front of the bullet before it hits the wall? I would have already calculated the raycast destination…
Bullets in my game are not instantaneous. They are visible (like an old skool shooter)
$$anonymous$$ind of like the rockets in $$anonymous$$ario ? In that case, you could cast a ray every X seconds with a coroutine or InvokeRepeating.
As for the trigger, as far as I know the entre event is raised when a rigidbody enter the trigger, not the other way around. So a moving target would raise it, but not a static one.
Answer by GC1983 · May 06, 2012 at 05:50 AM
OnTriggerEnter will work fine. Tag whatever you are shooting at something like Enemy or Target and attach the script the bullet itself.
function OnTriggerEnter(collider : Collision)
{ if(collider.gameObject.tag = "Enemy") { Destroy(this.gameObject); } }
That should be it.
Answer by Rrrush5000 · Aug 01, 2017 at 04:08 PM
this is C# and this works for me
using UnityEngine; using System.Collections;
public class Mover : MonoBehaviour { public float speed; public int damage = 5;
void Start ()
{
GetComponent<Rigidbody2D>().velocity = transform.right * speed;
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag == "Enemy")
{
collision.collider.gameObject.GetComponent<Enemy>().Damage (damage);
Destroy (gameObject);
}
if(collision.collider.gameObject)
{
Destroy (gameObject);
}
}
}