Search Unity

Translate

Discussion in 'Scripting' started by DiegoC, Jan 7, 2012.

  1. DiegoC

    DiegoC

    Joined:
    Jan 14, 2011
    Posts:
    36
    Hi
    I want to move an object (wall) automatically in the axis Z , (n =value)
    I use the function "transform.Translate( Time.deltaTime*speed ,0, 0); but How I stop the object when I move or translate (n)
    Thanks in advance
     
  2. Ted-de-Munnik

    Ted-de-Munnik

    Joined:
    Mar 13, 2011
    Posts:
    119
    you stop calling the translate function, you can save the position where you started, and compare the z distance to the current z distance and stop when its n or bigger
    Code (csharp):
    1.  
    2. private Vector3 startPosition;
    3. private float wantedDistance;
    4. private float speed;
    5. void Start(){
    6. startPosition = transform.position;
    7. }
    8. void Update(){
    9. if(Mathf.Abs(startPosition.z - transform.position.z) > wantedDistance){
    10. transform.Translate(0, 0, speed*Time.deltaTime);
    11. }
    12. }
    13.  
    The problem with this code however, is that it checks every frame for a movement that may take only a couple of seconds. You may want to disable the script when it is done, or run this in a coroutine. I wanted to have the code as simple as possible, as an example.