Problem with for loop

The code below is activated when a moving cube hits a wall that has been set as a trigger. It is supposed to make the cube back up from the wall a little bit and it does do that. The problem is that is happens instantly. It looks like the cube teleports backward. I tried increasing the value of x but that only made the cube teleport back further.  Any idea why it is teleporting back rather that slowly moving backwards? Thanks in advance!


private void OnTriggerEnter()
{
hit = Random.Range(50, 750);

for (int x=50; x > 0; x-- )
{
transform.Translate(0,0,-1 * Time.deltaTime);      
}
}


  • Jonathan Gonzalez(jgonzalez) replied

    I'm a bit confused on what you mentioned. So the object that has the trigger is supposed to move back 1 unity along the negative z axis? That's what your script is saying. If you want the object that enters the trigger to move back then you'll need to use the parameters of the OnTriggerEnter.

    If you want the object within the trigger to slowly move away from the trigger zone then you can use OnTriggerStay instead. It'll continue to move the object as long as it's within the trigger zone. OnTriggerEnter only gets called whenever it detects an object initially.

    To better understand this use a Debug.Log within your OnTriggerEnter, within the for loop and you'll see why it teleports:

        void OnTriggerEnter ()
        {
            for (int x = 50; x > 0; x--) {
                transform.Translate (0, 0, -1 * Time.deltaTime);
                Debug.Log ("X is " + x);
            }
        
        }


    if you take a look at the console when the object enters the trigger, the X value goes from 50 down to 1 very very quickly, almost instantly. 

    With OnTriggerStay it'll continue to move the object as long as it's still within the trigger. So it'll move as expected. Of course in this case you'd want to move the object that entered the trigger and not the trigger itself so use this:

    void OnTriggerStay (Collider col)
        {
            col.transform.Translate (0, 0, -1 * Time.deltaTime);   
    
        }


    You won't need to use the for loop as it'll basically do the same thing with the OnTriggerStay. I added the Collider col parameters and used that as the object to move. 

    If you're looking for something else let me know.