I’m making a top down shooter and I’m using Ray cast to be fired from the enemy to the player but when I test the game and I get in the range of the enemy to either attack or chase me they just freeze up. and if I’m completely out of their range they walk around like they should. This is my first time using ray casts so I’m not sure if I did something wrong.
here is my code:
Vector3 startRay = transform.position;
Vector3 rayDirection = player.transform.position;
RaycastHit hit;
//Check for sight and attack range
playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if (!playerInSightRange && !playerInAttackRange)
{
Patroling();
}
if (playerInSightRange && !playerInAttackRange && Physics.Raycast(startRay, rayDirection, out hit, sightRange))
{
if (hit.collider.tag == "Player")
{
ChasePlayer();
}
}
if (playerInAttackRange && playerInSightRange && Physics.Raycast(startRay, rayDirection, out hit, attackRange))
{
if (hit.collider.tag == "Player")
{
AttackPlayer();
}
}
My ChasePlayer function:
private void ChasePlayer()
{
agent.SetDestination(player.position);
}
my AttackPlayer function:
private void AttackPlayer()
{
agent.SetDestination(transform.position);
transform.LookAt(player);
if (!alreadyAttacked)
{
Instantiate(projectile, transform.Find("BulletSpawn").position,
transform.Find("BulletSpawn").rotation);
alreadyAttacked = true;
Invoke(nameof(ResetAttack), timeBetweenAttacks);
}
}