I’ve been working on this all day and can simply not find what the problem is, I’ve looked all over unityAnswers and have not found a working solution, though I seem to be getting closer. Whenever I use a the following my object will move down to the correct position and then at the end suddenly jump to the origin. It’s the most infuriating thing. I’ve done some prints to try to figure out what exactly happens and everything works until the very end. After that I can no longer move it down and it moves up to the wrong place. It’s so nutty.
if(Input.GetButtonDown("up") && transform.position.y < 40 && !movingUp)
{
var targetPosY : Vector3 = Vector3(transform.position.x, transform.position.y + 40, transform.position.z);
movingUp = true;
print("on up" + targetPosY);
}
if(movingUp && transform.position.y < targetPosY.y)
{
MoveObject(transform.position,targetPosY, 0.5f);
if(transform.position.y >= targetPosY.y)
{
//transform.position.y = targetPosY.y;
movingUp = false;
}
//print("upB" + movingUp);
}
if(Input.GetButtonDown("down") && transform.position.y > -70 && !movingDown)
{
//var currentNegY : Vector3= Vector3(transform.position.x, transform.position.y, transform.position.z);
var targetNegY : Vector3 = Vector3(transform.position.x, transform.position.y - 40, transform.position.z);
movingDown = true;
print("on down" + targetNegY);
}
if(movingDown)
{
MoveObject(transform.position,targetNegY, 0.5f);
//transform.Translate(Vector3.down * 1);
if(transform.position.y <= targetNegY.y)
{
transform.position.y = targetNegY.y;
movingDown = false;
}
//print("downB" + movingDown);
print("on down" + targetNegY);
}
function MoveObject (startPos : Vector3, endPos : Vector3, time : float) {
var i = 0.0;
var rate = 1.0/time;
while (i < 1.0)
{
i += Time.deltaTime * rate;
transform.position = Vector3.Lerp(startPos, endPos, i);
yield;
}
}
Sorry about the trashy code, I’ve tried so many things in an attempt to get this to work. Help is greatly appreciated!