I’m trying to create a moving platform (or elevator) that moves back and forth between two positions, which are stored in vectors. I want to use Vector3.Lerp() to move them so that everything is really smooth.
Here’s the code I have (C#):
using UnityEngine;
using System.Collections;
public class Elevator : MonoBehaviour
{
// Declare variables
public Vector3 origin;
public Vector3 destination;
public float speed = 0f;
// Update is called once per frame
void Update ()
{
MoveElevator();
}
void MoveElevator()
{
Vector3 newPosition = destination;
// When elevator meets end position, reverse direction
if (origin.x >= destination.x origin.y >= destination.y origin.z >= destination.z)
{
newPosition = origin;
}else if (destination.x <= origin.x destination.y <= origin.y destination.z <= origin.z)
{
newPosition = destination;
}
// Move platform
transform.position = Vector3.Lerp(transform.position, newPosition, Time.deltaTime * speed);
}
}
Now, the problem I’m having is that when the platform reaches its destination target, it slows to a crawl and won’t reach the full integer, and thus it won’t flip the values and reverse the destination!
For example, I have the origin vector set at X:-5, Y:1.5, Z:-0.5, and the destination vector set at X:5, Y:3.5, Z:0.5, but the platform will never reach the full integer; it will stop at something like X:4.99985, Y:3.49998, Z:0.4997. Is there anyway I can fix this, or a better way to use Vector3.Lerp() to get the desired results?
MoveTowards at least makes it completely reach the final destination, but then it never actually flips the direction… Gonna try something real quick to see if that does something else…
EDIT: OK, it appears that my checks for if the platform reaches its destination are never performed?
EDIT 2: I just figured out what was wrong, and I fixed it! Here’s the updated code…
using UnityEngine;
using System.Collections;
public class Elevator : MonoBehaviour
{
// Declare variables
public Vector3 origin;
public Vector3 destination;
public float speed;
Vector3 newPosition;
void Start()
{
newPosition = destination;
}
// Update is called once per frame
void FixedUpdate ()
{
// When elevator meets end position, reverse direction
if (transform.position.x >= destination.x transform.position.y >= destination.y transform.position.z >= destination.z)
{
newPosition = origin;
Debug.Log("New Target Set At " + newPosition);
}else if (transform.position.x <= origin.x transform.position.y <= origin.y transform.position.z <= origin.z)
{
newPosition = destination;
Debug.Log("New Target Set At " + newPosition);
}
// Move platform
transform.position = Vector3.MoveTowards(transform.position, newPosition, Time.deltaTime * speed);
}
}
You see, instead of checking the current position against the target destination, I was checking the “origin” vector, which would NEVER change, hence the problem! Everything works perfectly now.