- Home /
How do I fix my platform-moving code?
I have written code to make a box move back and forth on the X axis, like a moving platform. When I run it, I get a message that my box is at the origin. (I wrote the error message, but it's obviously an error.) The box doesn't move either.
#pragma strict
//TODO: update to run on any axis
private var middlePosition : Vector3;
private var startPosition : Vector3;
private var endPosition : Vector3;
private var directionInput : String;
//find move radius
var moveRadius : float = 3.0;
//wait time (in sec)
var timeToWait : float = 1.5;
var speed : float = 1.0;
private var speedFrame;
speedFrame = speed * Time.deltaTime;
function Start ()
{
getStartingPosition();
Debug.Log("Starting Position is: " + startPosition + ".");
}
function Update ()
{
findStartAndEnd("negative");
LerpThatThing(startPosition, endPosition, speedFrame);
WaitForSeconds(timeToWait);
findStartAndEnd("zero");
LerpThatThing(startPosition, endPosition, speedFrame);
findStartAndEnd("positive");
LerpThatThing(startPosition, endPosition, speedFrame);
WaitForSeconds(timeToWait);
findStartAndEnd("zero");
LerpThatThing(startPosition, endPosition, speedFrame);
}
function getStartingPosition ()
{
middlePosition = transform.position;
}
function findStartAndEnd (directionInput)
{
startPosition = middlePosition;
if (directionInput == "negative")
{
endPosition = middlePosition - (moveRadius * Vector3.right);
}
else if (directionInput == "positive")
{
endPosition = middlePosition + (moveRadius * Vector3.right);
}
else
{
endPosition = middlePosition;
}
}
function LerpThatThing (startPosition, endPosition, speed)
{
transform.position = Vector3.Lerp(startPosition, endPosition, speed);
}
What's wrong with this? I thought it was a scope error, but changing variables didn't fix it.
PS: Lerp is a funny word.
Answer by Maerig · May 01, 2014 at 06:59 AM
Check the documentation.
Lerp stands for Linear Interpolation. In your case, its third parameter represents how much the platform has moved between startPosition and endPosition, as a float between 0 and 1. Here is how you should use it :
Vector3.Lerp(startPosition, endPosition, elapsedTime / totalDuration);
Where elapsedTime
is a float which you increase by Time.deltaTime
at each frame, and totalDuration
the total duration of the movement (you can compute it from the speed : totalDuration = Vector3.Distance(startPosition, endPosition) / speed
).
Also, this would probably fit in a coroutine.
So how would I move an object from a starting point to an ending point over a certain amount of time? Is Lerp the incorrect function to use?