Using LERP to define specific set of points instead of Trigger

The way my level design is set up, with a flying enemy as well, the periscope method would not work as the enemy would always somehow touch the ground if the level moves up a square or two.

Instead I created a parent game object, nested the enemy inside, and created two empty game objects to act as the start and end points.

Using LERP the enemy moves between the two points, wherever they’re set to.

public class EnemyMovement : MonoBehaviour
{
    [SerializeField] [Range(0.1f,1f)] float moveSpeed = 1f;
    [SerializeField] Transform start;
    [SerializeField] Transform end;
    [SerializeField] Transform enemySprite;

    Rigidbody2D rb;
    float positionPercent;
    int direction = 1;
   

    

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();    
    }

    void Update()
    {
        MoveEnemyLerp();
    }

    void MoveEnemyLerp()
    {
        positionPercent += Time.deltaTime * direction * moveSpeed;

        enemySprite.position = Vector3.Lerp(start.position, end.position, positionPercent);

        if (positionPercent >= 1 && direction == 1)
        {
            direction *= -1;
            transform.localScale = new Vector2(direction, 1f);

        }
        else if (positionPercent <= 0 && direction == -1)
        {
            direction *= -1;
            transform.localScale = new Vector2(direction, 1f);

        }

        
    }
}

Privacy & Terms