Search Unity

AI Distance Checking

Discussion in 'Scripting' started by DRRosen3, Feb 10, 2018.

  1. DRRosen3

    DRRosen3

    Joined:
    Jan 30, 2014
    Posts:
    683
    I'm having the dilemma where I'm trying to have my AI check to see if it has chased down the player enough in order to attack. In the FixedUpdate method I've tried the following methods.

    Checking the distance between the transforms of both the AI and the player to see if the distance is less than 0.1f. The problem with this, is that the transform.position represents the center point of the entire GameObject...but the mesh might be so large (making the collider so large) that the AI can never get close enough to the transform.position to think that it's in range.

    Checking the distance between the closest points on the CharacterController colliders of both the AI and the player to see if the distance is less than 0.1f. This results in the AI trying to get closer, even when they're already touching.

    Checking the distance between the closest points on the bounds of both the AI and the player's SkinnedMeshRenderers to see if the distance is less than 0.1f. This results in the AI trying to get closer, even when they're already touching.

    Thoughts? Solutions?
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Have a trigger collider that extends to your desired distance/dimensions?
     
  3. DRRosen3

    DRRosen3

    Joined:
    Jan 30, 2014
    Posts:
    683
    I THINK I have it solved. So far it's working well. I'm using the Insercets bool method that's native to the CharacterController's collider.bounds. It checks to see if your charactercontroller collider's bounds intersect with that of another.
     
  4. codeblue00

    codeblue00

    Joined:
    Nov 7, 2017
    Posts:
    2
    Had this same problem, except with multiple sizes of "enemy" mesh's, agent's, interactable sizes being different etc. I ended up solving my issue a lot of different ways depending on the situation...If your Player is using a NavMeshAgent resetting your player agent.stoppingDistance according to the raycasts hit tag, mask or whatever is an easy out. You could also do Physics.OverLapSpheres/boxes or multiple overlaps ie an aggroCollider array with a radius of 10f, and an attackCollider array at 3f then if attackCollider.Length > 0 to attack or whatever from the distance of 3f. Also you could just do Vector3 distToTarget = (this.transform.localPosition - target.transform.localPosition).normalized; or use Vector3.Distance (transform.localPosition , other.transform.localPosition);.
    Then check if(distToTarget <= 3f) { do this; }
    and just figure out the correct distance for each enemy etc..
    You could also adjust the Default Contact Offset, the solveriterations, etc for collisions in the Physics manager in Project Settings > Physics going to close can cause some janky stuff though lol.
     
    Last edited: Feb 11, 2018