SphereCastAll sees for miles

Hey Guys and Girls,

I am using this line of code

hits = Physics.SphereCastAll(transform.position,transform.localScale.x / 3,playerTransform.position - transform.position, Vector3.Distance(playerTransform.position, transform.position));

to help me enemies spot me!

It works fine and all, but it does mean they can see me from literally hundreds of miles away. I tried writing the code like this,

	hits = Physics.SphereCastAll(transform.position,transform.localScale.x / 3,playerTransform.position - transform.position, 10000f);

but then they don’t seem to see me at all, I have to get right in there face for it to work!

Can anyone suggest what I am doing wrong.

Thanks in advance!

You can use another approach with first checking distance between your player and the enemy:

if(Vector3.Distance(player.position, enemy.position) < range)
{}

then you check for a linecast between the two:

if (!Physics.Linecast (enemy.position, player.position, layerMask)) 
{}

My advice, place a GO at the level of the eyes of the enemy and use it as starting point.
The layerMask will ignore the enemy itself if the linecast is starting from inside a collider of the enemy.

You can see more here unitygems.com - unitygems Resources and Information.
The article also includes line of sight so that the enemy does not see you when you are behind him.

Hi Mr Steve,

One approach many people use is a sphere collider set to Is Trigger?. You then have an OnTriggerEnter() function call the “Attack” function.

I personally tend to use a combination of dot and distance, but I cant remember the exact script (@work) - if required I will post it when I get home.