Question by 
               adiolatez · Apr 05, 2021 at 06:56 PM · 
                c#2d2d gamemovement script2d-physics  
              
 
              2D AI movement
Hello! I'm quite new at programming and I have issue with my simple enemy AI. It should start chasing player when you get too close, and stop chasing when you either get far enough or when enemy moves too far away from its starting location. It kinda works, but when you get to border where enemy is too far away from its starting position, but too close to player it starts glitching and vibrating which looks weird. I would like enemy to start moving back to its starting position when it goes too far from its starting location.
 // Start is called before the first frame update
 void Start()
 {
     rb = this.GetComponent<Rigidbody2D>();
     startPos = this.transform.position;
 }
 // Update is called once per frame
 void Update()
 {    // Enemy seeks player
     float dist = Vector3.Distance(enemy.position, player.position);
     float startDist = Vector3.Distance(enemy.position, start.position);
     if (dist < 80 && startDist < 100)
     {
         Vector3 direction = player.position - enemy.position; // Enemy react to players movements
         direction.Normalize(); // Enemy keeps its course
         movement = direction;
     }
     else if (startDist > 1)
     {
         Vector3 direction = start.position - enemy.position;
         direction.Normalize();
         movement = direction;
     }
     
 }
 private void FixedUpdate()
 {
     moveEnemy(movement);
     
     void moveEnemy(Vector2 direction)
     {
         float dist = Vector3.Distance(enemy.position, player.position);
         float startDist = Vector3.Distance(enemy.position, start.position);
         {
             
             
                 if (dist < 80 && startDist < 100)
                 {
                     rb.MovePosition((Vector2)enemy.position + (direction * moveSpeed * Time.deltaTime)); // Moves enemy towards player
                 }
                 
                 else if (startDist > 1)
                 {
                     rb.MovePosition((Vector2)enemy.position + (direction * moveSpeed * Time.deltaTime)); // Moves enemy back to start
                 }
                 else if (startDist > 1) {
                     this.transform.position = startPos; // Resets enemy location
                     
                 }
             }
         }
     }
 }
               Comment
              
 
               
              Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                