- Home /
Stopping bullets from outside forcefield
Hi,
I'm trying to create a force field around a defense tower that stops bullets that are shot from outside of it's reach, to force players to go inside to be able to attack. What's happening now is example B, I want the behaviour of example A.
The forcefield has a sphere collider set as a trigger, so I thought of detecting if the object was a bullet in OnTriggerEnter and if so, destroy it, but OnTriggerEnter is also called when the bullet is spawn already inside the trigger anyway.
I was wondering if anyone could point me in the right direction.
Thanks in advance.
Answer by Creeper_Math · Dec 31, 2016 at 03:21 PM
Try putting in a "if" statement to test for the distance of the shell
float Forcefield Radius;
float Gap; // Increase this if the shells are going through the forcefield from the outside
void OnTriggerEnter(collider c) {
if (Vector3.Distance(c.transform.position, transform.position) > Radius - Gap) {
Destroy(c.gameObject);
}
}
Answer by salex100m · Jan 02, 2017 at 08:40 PM
Here's a better way, use raycasting from the bullet/gun. Raycast will NOT detect a collision if it is already inside the shield collider.
It seems like the raycast was made with your problem in mind already, so it would be the most elegant solution
Your answer
![](https://koobas.hobune.stream/wayback/20220612103720im_/https://answers.unity.com/themes/thub/images/avi.jpg)