- Home /
OnTriggerEnter problems
I have the function OnTriggerEnter on one of my bullet objects. The strange thing is, it works against one type of enemy when the enemy is moving, has a trigger, and has a rigidbody. It also works on another type when the enemy is stationary, has a trigger, and the bullet has the rigidbody. However, it does not work on both enemies at the same time. I have no idea why this is happening. The description of OnTriggerEnter is that only one object needs a rigidbody and only one needs a trigger enabled, but that isn't working for me. How can I get this to work?
Answer by e-bonneville · Mar 28, 2010 at 07:18 PM
Well, if the enemy is flying towards you, and the bullet is flying towards the enemy, it's possible that the bullet is moving so fast compared to the enemy's velocity that it actually isn't entering the trigger at all - this can happen when the object is moving so fast that one frame, it's next to the enemy, and the next, has passed through it! There are several ways to fix this. Option 1 is to make the trigger bigger. Another (unacceptable in most cases) option is to decrease the speed of the bullet and the enemy. The third option is to use raycasts. This detects whatever is in front of the bullet, and tells it to explode several frames before actual contact. This code should do the trick - put it on your bullet:
function Update () {
var hit : RaycastHit;
if (Physics.Raycast (transform.position, Vector3.forward, hit, 5.0)) {
//Put your explode script here.
}
}
If it still isn't working, increase the size of your trigger, or increase the size of the third variable (the 5). Hope this helps!
The problem isn't that it isn't hitting it's target. The problem is I can only code it to hit one target or another, not both.
Can your show us your bullet code? It is hard to guess why without seeing any scripts.
Answer by equalsequals · May 23, 2010 at 10:56 PM
I'm not sure if I am understanding this right, but you have a specific scenario where a single bullet can hit multiple enemies at the same time?
It looks to me as you are using the bullet to detect "hey, I hit something", again, I'm not sure if I am understanding correctly but maybe you should consider working it the opposite where your enemies say "hey, I was hit by something" and act accordingly.
With this method you will still be able to access things you need to do in the bullet's behaviour's as you will still have reference to the bullet (atleast its collider component) upon OnTriggerEnter()
Hope that helps.
==
Answer by NZRoadKill · Jul 19, 2010 at 03:14 PM
Check out this page. On there you will find an interaction chart that shows what type of combinations of colliders/triggers can interact. You may have an issue depending on your setup.
http://unity3d.com/support/documentation/Manual/Physics.html