Search Unity

Question How can I make an enemy move to a location?

Discussion in 'Scripting' started by JialeHe28, Mar 16, 2023.

  1. JialeHe28

    JialeHe28

    Joined:
    Sep 16, 2022
    Posts:
    9
    I'm trying to write a script that moves a flying enemy back to its original position.
    Code (CSharp):
    1.   private void ReturnPosition()
    2.     //Provoca que los enemigos vuelvan a su posición inicial.
    3.     {
    4.      
    5.         _rigidbody.velocity = ((_initialPosition-(Vector2)transform.position).normalized*_enemySpeed);
    6.     }
    7.  
    This is the code and it mostly works but it can't get back to its exact original position and when it reaches that point, it starts to stutter. I'm using RigidBody so the enemy is affected by collisions but can't seem to find a proper solution for this.

    Code (CSharp):
    1. case Estados.regresar:
    2.                 ReturnPosition();
    3.              
    4.                 if (_myEnemyFOV.GetDetected())
    5.                 {
    6.                     _estado = Estados.perseguir;
    7.                 }
    8.  
    9.                 if (Mathf.Approximately(transform.position.x, _initialPosition.x)&&Mathf.Approximately(transform.position.y,_initialPosition.y))
    10.                 {
    11.                     _estado = Estados.patrullaje;
    12.                 }
    13.                 break;
    What I want is that once it reaches it's original position, it starts patrolling again but tt can't seem to go to that exact point
     
  2. Chubzdoomer

    Chubzdoomer

    Joined:
    Sep 27, 2014
    Posts:
    132
    I personally wouldn't use Mathf.Approximately for something like that. Try using Vector2.Distance instead to compare the enemy's current position with its starting position, and if the result is incredibly small (say, 0.05f or less) then it has essentially reached its destination.