- Home /
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);
}
}
Answer by JoeStrout · Apr 20, 2015 at 05:06 PM
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!
Yeah I've only just recently started to learn about the lerp methods, i'll give it a try now. Thanks for the swift answer!
Thanks, it didn't work at first but that's due to my own logic being flawed. I've updated the OP with the working script for anyone else who might like to know the correct way to do it.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
moving the main game window 0 Answers
Placing player relative to object,Placing the player relative to an object 2 Answers