I can't quite understand how Physics.OverlapSphere works at this point. As shown below in the code, if the player enters the overlapsphere then it should return true, but I keep getting false when the player enters the sphere. This is the script that call the method
void Update()
{
float distance = Vector3.Distance(target.position, transform.position);
if (distance <= lookRadius)
{
agent.SetDestination(target.position);
if (distance <= agent.stoppingDistance)
{
CharacterStats targetStats = target.GetComponent<CharacterStats>();
Debug.Log(enemy.onPlayerEnter());
if (targetStats != null && enemy.onPlayerEnter())
{//if player exist and the player enters the attack area
Combat.Attack(targetStats);
}
FaceTarget();
}
}
animator.SetFloat("speed", agent.velocity.magnitude);
this is the script of the method:
public bool onPlayerEnter()
{
Collider[] hitColliders = Physics.OverlapSphere(interactionTransform.transform.localPosition, radius);
//Debug.Log(interactionTransform.transform.localPosition);
for(int i = 0; i < hitColliders.Length; i++)
{
if(LayerMask.LayerToName(hitColliders[i].gameObject.layer) == "Player")
{
Debug.Log("Player enter");
return true;
}
}
return false;
}
//visualize the overlapsphere
private void OnDrawGizmosSelected()
{
if (interactionTransform == null) interactionTransform = transform;
Gizmos.color = Color.cyan;
Gizmos.DrawWireSphere(interactionTransform.position, radius);
}
collider with monster [Collide with player[][1]][2]
https://i.sstatic.net/8Fgh0.png https://i.sstatic.net/jnubp.png
For unknown reason, I found that the overlapsphere works at certain position in the map, but the rest of the position does not work at all. I think this probably is a bug in Unity.
Your sphere gizmo and actual sphere are different: for drawing gizmo you use transform.position, but for overlap sphere - transform.transform.localPosition (no need to double like transform.transform, and position and localPosition can be very different). I think, this is the answer.
Its easy to get mess with LayerMask, its a good approach, but for testing you better use tag, or gameObject.InstanceID, or even gameObject.name. But its minor, in general it looks like you deal with layers right.
Be sure that your agent.StoppingDistance not set too small
It`s a bad practice to use GetComponent every frame, as you do for get targetStats.