Search Unity

Make an object smoothly follow player's Y position

Discussion in 'Scripting' started by bernardp, Jun 19, 2019.

  1. bernardp

    bernardp

    Joined:
    Apr 28, 2017
    Posts:
    23
    I have an enemy object that follows the player all the time. If the player is chased, the distance between the enemy and player gets smaller. If the player should no longer be chased, the distance gets bigger.

    The Y position of the enemy and player is always the same but I want to create a delay - for example, if player jumps then his Y position changes and the enemy should change to the same Y position, but he should reach that Y position a bit slower than player. Sort of like a searchlight that follows something, but only on Y coordinate.

    This is my code in Update() function of enemy:

    Code (CSharp):
    1. if (player)
    2.         {
    3.             if (player.playerHealth > 0)
    4.             {
    5.                 if (chasePlayer)
    6.                 {
    7.                     rb.velocity = new Vector2(player.moveSpeed * 1.5f, player.GetComponent<Rigidbody2D>().velocity.y);
    8.                 }
    9.                 else
    10.                 {
    11.                     rb.velocity = new Vector2(player.moveSpeed * (-1.2f), player.GetComponent<Rigidbody2D>().velocity.y);
    12.                 }
    13.             }
    14.             else
    15.             {
    16.                 transform.position = Vector3.MoveTowards(transform.position, player.transform.position, Time.deltaTime * player.moveSpeed);
    17.             }
    18.  
    19.         }
    20.  
    21.         //Stop from getting close to player
    22.         if (transform.position.x > moveForwardPoint.transform.position.x)
    23.         {
    24.             transform.position = new Vector2(moveForwardPoint.transform.position.x, player.transform.position.y);
    25.         }
    26.  
    27.         //Stop from getting too far from player
    28.         if (transform.position.x < moveBackPoint.transform.position.x)
    29.         {
    30.             transform.position = new Vector2(moveBackPoint.transform.position.x, player.transform.position.y);
    31.         }
    You can see that enemy has smaller speed than player when he is not chasing and bigger speed than player when he is chasing. In lower part of code I check if the enemy doesnt get too far or too close to the player.

    How could I do that so that enemy follows the player on Y position, but slower?

    I was suggested to use Vector3.SmoothDamp but I don't know how to use it.