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);
}
}