- Home /
Fast bullet ignor collision sometimes
hi, i'm making a side-scroll game so the player can shoot in 2 directions, i made everything and i made a bullet with OnTriggerEnter() function to make it destroy it self if collided with triggers , its good but sometimes the bullet just keep moving and don't destroy it self, is there any other way to do this without OnTriggerEnter(), Maybe?
Answer by FTheCloud · Sep 10, 2011 at 06:26 PM
Take this script and attach to your bullet prefab. then just check the layers that you want the bullet to collide with.
pragma strict
var layerMask : LayerMask; //make sure we aren't in this layer var skinWidth : float = 0.1; //probably doesn't need to be changed private var minimumExtent : float; private var partialExtent : float; private var sqrMinimumExtent : float; private var previousPosition : Vector3; private var myRigidbody : Rigidbody; //initialize values function Awake() { myRigidbody = rigidbody; previousPosition = myRigidbody.position; minimumExtent = Mathf.Min(Mathf.Min(collider.bounds.extents.x, collider.bounds.extents.y), collider.bounds.extents.z); partialExtent = minimumExtent*(1.0 - skinWidth); sqrMinimumExtent = minimumExtent*minimumExtent; }
function FixedUpdate() { //have we moved more than our minimum extent? var movementThisStep : Vector3 = myRigidbody.position - previousPosition; var movementSqrMagnitude : float = movementThisStep.sqrMagnitude; if (movementSqrMagnitude > sqrMinimumExtent) { var movementMagnitude : float = Mathf.Sqrt(movementSqrMagnitude); var hitInfo : RaycastHit; //check for obstructions we might have missed if (Physics.Raycast(previousPosition, movementThisStep, hitInfo, movementMagnitude, layerMask.value)) myRigidbody.position = hitInfo.point - (movementThisStep/movementMagnitude)*partialExtent; } previousPosition = myRigidbody.position; }
What this does is use raycasts to avoid passing through an object.
Answer by unluckyBastard · Sep 11, 2011 at 04:30 AM
you should use raycasts for bullet hit detection, avoid using collisions for fast moving objects...
Your answer
![](https://koobas.hobune.stream/wayback/20220612210447im_/https://answers.unity.com/themes/thub/images/avi.jpg)