Enemy Lerping between two Vectors

Hi all,

I’ve got a quick question, hoping someone can enlighten me as to why it’s not functioning correctly. Probably doing something wrong knowing me!

I’m trying to slide an enemy left and right on the x-axis. I’ve watched and read a few things on Vector3.Lerp but I’m finding it difficult to implement it.

Currently the enemy moves into a position, but never actually reaches the value I’ve set. Please take a look at the script below.

EDIT: The script below now works, credit to JoeStrout for the help. Hopefully someone will find this useful.

using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour {

    public float moveSpeed = 0.5f;

    private Transform self;
    private Vector3 newPos;

    void Awake() {
        self = transform;
        newPos = new Vector3(-2, transform.position.y);
    }
	
	// Update is called once per frame
	void Update () {
        SlideEnemy();
	}

    void SlideEnemy() {
        Vector3 posA = new Vector3(-2, transform.position.y);
        Vector3 posB = new Vector3(2, transform.position.y);
        if (transform.position == posA) {
            newPos = posB;
        }
        else if (transform.position == posB) {
            newPos = posA;
        }
        
        gameObject.transform.position = Vector3.MoveTowards(transform.position, newPos, Time.deltaTime * moveSpeed); 
    }
}

Yep, that’s an abuse of Lerp, all right. Lerp takes a starting point, an ending point, and how far you want to be from one to another. It never takes the current position as any of its parameters. So if you find yourself passing in the current position, you need to step back from that ledge.

In this case – and many others where Lerp is abused – what you probably want is Vector3.MoveTowards. That takes the current position, where you’re trying to go, and how far you’re willing to move on this frame. These are the three parameters you’re already using; so use the correct function, and you should be all set!