Collision Detection issue
Hi all, Im really new to Unity (just started a few weeks ago) and Im making a simple FPS game in which the player has a gun and can shoot things. My problem is when I fire a bullet at an enemy, the collision detection sometimes works. Other times the bullet will go right through the enemy. I have the bullet set to detect if it hit an enemy and it works, but like I said, it only works sometimes. Am I using too high a speed for the bullet? Or is it something else? Please excuse my beginner mistakes! :) My code:
using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour
{
private float speed = 50.0f;
// Use this for initialization
void Start()
{
//...
}
// Update is called once per frame
void Update()
{
transform.Translate(0, 0, speed * Time.deltaTime);
}
void OnTriggerEnter(Collider other)
{
if(other.GetComponent<ReactiveTarget>())
{
Debug.Log("Target hit");
}
Destroy(this.gameObject);
}
}
Answer by rutter · Nov 09, 2015 at 06:31 AM
You may want to set up continuous collision detection. The default "discrete" mode checks collision once per frame, and may miss fast-moving objects like bullets. Continuous collision is more expensive on the CPU, but catches things like this.
It works just a little better, but the bullet still manages to pass through the enemy at some points.. D: Even with the enemy set to continuous and the bullet to continuous dynamic, the same issue is still present! Any other suggestions or ideas?
You can make the collider of the bullet longer, or use a raycast to scan ahead of the bullet each frame.
Stretching the collider would be simpler, and doesn't require changing the visible model or any extra code. It could potentially have issues with rapid fire unless you set the bullets to their own layer and use the Physics $$anonymous$$anager to disable collisions with each other. You would also have to be careful about the collider triggering on the shooter if they start close to it.
Raycasting would allow you to remove the collider and rigidbody from the bullets so there's less work being done by the physics system, and ins$$anonymous$$d scan ahead of the bullet for potential impacts. You'd have to calculate the distance the bullet would travel and have a ray slightly longer than that. It could have issues if the enemy can move fast and the bullet ends up inside the enemy collider, since raycasts don't trigger on a collider if they start from inside it.
Your answer
Follow this Question
Related Questions
How to make SphereCastAll retrieve all hits with a concave mesh ? 0 Answers
Spawned objects sink through ground, when over 3 clones 0 Answers
How to determine on collision if an object is rotated in a certain way 1 Answer
Intersecting edge colliders cause particles to pass through one edge collider? 1 Answer
How To create 2D collision detection on object which changes dimensions 1 Answer