Search Unity

object moving forward for certain distance only.

Discussion in 'Scripting' started by Patrk, Nov 13, 2018.

  1. Patrk

    Patrk

    Joined:
    Apr 9, 2017
    Posts:
    48
    I have a simple piece of code below that makes an animated on the spot/treadmill animal move forward. I want to make it so the animated animal object only moves forward for about 20 iterations/or 20 steps only, as otherwise it walks off the edge of the world. What is the easiest way to do this by adding to the code below? thanks


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class Mover : MonoBehaviour
    4. {void Update(){
    5.      transform.Translate(0, 0, Time.deltaTime);
    6.        // this would add the delta time each frame to the z position of the object this script is attached to

    7.     }
    8. }
    9.  
     
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,778
    Wouldn't be better to test against distance to travel. Or xyz boundaries for example?
    Does it have to be steps?
     
  3. Patrk

    Patrk

    Joined:
    Apr 9, 2017
    Posts:
    48
    Hi,
    No it doesn't have to be steps, just an approx distance from the starting point/equivalent of 20 steps etc..
     
  4. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,778
    If you want just steps, then you just need an iterator.
    Either condition when iteration has changed, comparing previous iteration state.
    Or when step changed.
    Or move, until xyz position is reached.
    Or xyz is not exceeded.
    For example
    Code (CSharp):
    1. if ( transform.postion.x > - 120 && transform.postion.x < 120 )
    2. {
    3.     // do some movement here
    4. }
    The easiest and safest is knowing boundaries of the map.
    Or distance to obstacle, edge etc.
     
  5. Patrk

    Patrk

    Joined:
    Apr 9, 2017
    Posts:
    48
    ok thanks will look at that.