Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

moving back and forth on one axis

Discussion in '2D' started by andreas_mavromm, Sep 19, 2019.

  1. andreas_mavromm

    andreas_mavromm

    Joined:
    May 9, 2019
    Posts:
    14
    Hey everybody,

    I am trying to get an object to move back and forth on the X-axis (with no change in Y), similar to a moving platform you would find in any platformer.... I would use the MoveTowards function, but the only problem is that the MoveTowards function causes movement on both the X and Y axis, and I only want the moving object to move in a straight line back and forth across the screen.

    So far I have this:

    public GameObject objectToMove;
    public float leftXPoint;
    public float rightXPoint;
    public float moveSpeed;
    public Vector2 startDirection;
    public Vector2 changedDirection;


    void Update()
    {
    objectToMove.transform.position += new Vector3(startDirection.x * moveSpeed * Time.deltaTime,
    startDirection.y * moveSpeed * Time.deltaTime, 0f);
    if (objectToMove.transform.position.x >= rightXPoint)
    {
    objectToMove.transform.position += new Vector3(changedDirection.x * moveSpeed * Time.deltaTime, changedDirection.y * moveSpeed * Time.deltaTime, 0f);
    }
    if (objectToMove.transform.position.x <= leftXPoint)
    {
    objectToMove.transform.position += new Vector3(startDirection.x * moveSpeed * Time.deltaTime,
    startDirection.y * moveSpeed * Time.deltaTime, 0f);
    }
    }

    I have set startDirection to 1, 0 and changedDirection to -1, 0..... so that the object, as soon as it is instantiated, moves RIGHT in a straight line. However, when it reaches the point I have set for the right X point, the object simply STOPS and does not turn around and move in the other direction.

    Any help?