I have a projectile prefab that’s fired from my player to shoot an enemy prefab. The projectile is destroyed upon collision, and after three hits the enemy is destroyed as well.
Most of the time it works fine, but sometimes the projectiles will pass through the enemy prefab without colliding. I haven’t been able to determine any kind of pattern that tells me when this will or won’t happen, and it essentially seems random.
Any suggestions on what might cause this, so I can look into finding the issue and a solution?
Chuck all your “Physic” related code in the FixedUpdate function rather than update. Then the your projectiles will be taken care of at the same time as collisions.
If your projectile’s velocity is too high, collision detection will become unable to detect collisions.
But there is a workaround for this using raycasts:
using UnityEngine;
using System.Collections;
public class BallisticsMechanic : MonoBehaviour
{
public float bullet_firing_velocity,gravity,bullet_damage; //variables
private Vector3 bullet_velocity = new Vector3 (0, 0, 0); //the vector that contains bullet's current speed
private Vector3 last_position = new Vector3(0,0,0), current_position = new Vector3 (0,0,0);
// Use this for initialization
void Start ()
{
gravity = 9.8f;
bullet_velocity = transform.forward * bullet_firing_velocity; //bullet velocity = forward vector * bullet firing velocity
/* linecasting */
current_position = transform.position;
DestroyObject (gameObject, 3); //destroy bullet after 3 sec's
}
void FixedUpdate ()
{
gameObject.rigidbody.velocity = bullet_velocity; //make the bullet's velocity equal to current velocity value
bullet_velocity.y -= gravity; //decrease the y axis of bullet velocity by amount of gravity
/* linecasting */
RaycastHit hit;
last_position = current_position;
current_position = transform.position;
if (Physics.Linecast(last_position, current_position, out hit))
{
hit.transform.SendMessage("AddDamage", bullet_damage, SendMessageOptions.DontRequireReceiver); //Send Damage message to hit object
}
Debug.DrawLine (last_position, current_position, Color.red);
}
}