- Home /
Rigidbody and Collision Conflict in FPS game
Hello, I am working on a simple FPS game. I am utilizing an enemy controller script which requires the use of a rigidbody for movement. The rigidbody and the EnemyController script are all found within the parent "Enemy" gameObject, while the collision is located within the respective child.
When the enemy gets shot, they should lose health. However, this is not functioning properly, as instead of shooting the child object, the rigidbody supersedes the box collider on the child object and causes the shot to reference the parent object. Therefore, I need the collision on the child object to reference the child in order for the script to work properly.
When debugging to see what object is "shot," this is the result:
While this is the result I expect (skull-1 is a child of the "Enemy" game object):
Here is the code for the "EnemyController":
public int health = 3;
public GameObject explosion;
public float playerRange = 10f;
public Rigidbody theRB;
public float moveSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Vector3.Distance(transform.position, PlayerMovement.instance.transform.position) < playerRange)
{
Vector3 playerDirection = PlayerMovement.instance.transform.position - transform.position;
theRB.velocity = playerDirection.normalized * moveSpeed;
}
else
{
theRB.velocity = Vector3.zero;
}
}
public void TakeDamage()
{
health--;
if(health <=0)
{
Destroy(gameObject);
Instantiate(explosion, transform.position, transform.rotation);
}
}
}
and here is a code snippet for shooting which references the EnemyController:
void Shoot()
{
if(currentAmmo > 0)
{
RaycastHit hit;
if(Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit))
{
Debug.Log(hit.transform.name);
Instantiate(bulletImpact, hit.point, transform.rotation);
if(hit.transform.tag == "Enemy")
{
hit.transform.parent.GetComponent<EnemyController>().TakeDamage();
}
}
gunAnim.SetTrigger("Shoot");
currentAmmo--;
}
}