Hi! I’m working on an FPS and I’m having trouble with headshots. currently guns operate on raycasts and when the raycast fires it checks for script components to apply damage etc. the enemy taking damage normally is fine, but the headshot doesn’t work. I have a cube parented to a capsule(the enemy) acting as my head collider, and for some reason when I check for the head script component on the head and call a function that sets a bool to true on the head, triggering an event that sets the enemy’s (capsule’s)health to zero, it doesn’t work. watching the variables during runtime, the bool on the head doesn’t even set to true.
this function handles the raycast
void Shoot()
{
//muzzle flash
particleSystem.Play();
//subtracts ammo
currentAmmo--;
//raycast
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
//finds if the object has the enemy script that handles health
Enemy target = hit.transform.GetComponent<Enemy>();
//finds if the object has the Head script that handles headshots
Head head = hit.transform.GetComponent<Head>();
//bodyshots, take normal damage
if (target != null)
{
target.TakeDamage(damage);
}
//headshot, in theory sets a bool headPop to true in the targeted head script
if (head != null)
{
head.Pop();
}
//applies a force if it can
if (hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * impactForce);
}
}
}
this function handles enemy health(on the enemy capsule)
public void TakeDamage(float amount)
{
//subtracts health
health -= amount;
//destroys the enemy (theres a function in update that handles a seperate die function, which is why the number is not zero)
if (health <= -25f)
{
Destroy(enemy);
}
}
and lastly, this is the headshot handler(on the head cube), should be super easy, not sure why it isn’t working
public class Head : MonoBehaviour
{
public bool headPop = false;
private void Update()
{
if(headPop == true)
{
Enemy enemy = gameObject.GetComponentInParent(typeof(Enemy )) as Enemy;
enemy.HeadPop();
}
}
public void Pop()
{
headPop = true;
}
}