0
votes

I'm new to Unity, and am trying to find a way to move a block forward for a set amount of time, then have it travel back to its starting position in that same amount of time. I'm using Time.deltaTime in order to move the block for a set amount of time, and this does work. However, once the countDown variable reaches 0 and the object has to start travelling back to its original position, the object stops moving and I'm not sure why.

public class Problem1 : MonoBehaviour { 
    float countDown = 5.0f;

    // Use this for initialization
    void Start () {

    }

    void Update () {
        transform.position += Vector3.forward * Time.deltaTime;
        countDown -= Time.deltaTime;

        if (countDown <= 0.0f)
            transform.position += Vector3.back * Time.deltaTime;
 }
}

I'm fairly certain that I'm using Vector3.back incorrectly, but I can't figure out how.

2

2 Answers

3
votes

It's because you are moving your object forwards and backwards at the same time. You only want to move it forward when countDown is greater than 0.
This is the code you need:

public class Problem1 : MonoBehaviour { 
    float countDown = 5.0f;

    // Use this for initialization
    void Start () {

    }

    void Update () {
        countDown -= Time.deltaTime;

        if(countDown > 0)
            transform.position += Vector3.forward * Time.deltaTime;
        else if (countDown > -5.0f) // You don't want to move backwards too much!
            transform.position += Vector3.back * Time.deltaTime;
 }
}
1
votes

The object stops moving because once the countDown reaches 0.0f, you are still moving it forward, but you are also moving it back.

in other words, you have code running that basically does this:

if (countDown > 0.0f) {
    transform.position += Vector3.forward * Time.deltaTime;
    countDown -= Time.deltaTime;
} else if (countDown <= 0.0f) {
    transform.position += Vector3.forward * Time.deltaTime;
    transform.position += Vector3.back * Time.deltaTime;
    countDown -= Time.deltaTime;

I would recommend running your code like this:

public class Problem1 : MonoBehaviour { 
float countDown = 5.0f;

// Use this for initialization
void Start () {

}

void Update () {
    if (countDown > 0.0f) {
    transform.position += Vector3.forward * Time.deltaTime;
    countDown -= Time.deltaTime;
}

    else if (countDown <= 0.0f) {
        transform.position += Vector3.back * Time.deltaTime;
    countDown += Time.deltaTime;
    }
}
}

in fact, an else statement would probably work better where the else if statement is, but I made it an else if statement for clarity.

Good luck!