Horizontal Movement 3D

Hi,

I followed the tutorial precisely however I couldn’t figure it out what’s I’m missing exactly. I have an object and I want to move it horizontally right and left in the area of 5 pixels.

Side Walk script:

 public float distance = 5;
 public bool horizontal = true;
 public float speed = 3f;
 public float offset = 0f;

 private bool isForward = true;
 private Vector3 startPos;

void Awake()
{
    startPos = transform.position;

    if (horizontal)
        transform.position += Vector3.right * offset;
    else
        transform.position += Vector3.forward * offset;
}

    void Update()
    {
            if (horizontal)
            {
                if (isForward)
                {
                    if (transform.position.x < startPos.x + distance)
                    {
                        transform.position += Vector3.right * Time.deltaTime * speed;

                    }
                    else
                        isForward = false;
                }
                else
                {
                    if (transform.position.x > startPos.x)
                    {
                        transform.position -= Vector3.right * Time.deltaTime * speed;
                    }
                    else
                        isForward = true;
                }
            }
            else
            {
                if (isForward)
                {
                    if (transform.position.z < startPos.z + distance)
                    {
                        transform.position += Vector3.forward * Time.deltaTime * speed;

                    }
                    else
                        isForward = false;
                }
                else
                {
                    if (transform.position.z > startPos.z)
                    {
                        transform.position -= Vector3.forward * Time.deltaTime * speed;
                    }
                    else
                        isForward = true;
                }
            }            
        }
}


Staring at code is not the same as debugging code. What if parts of the code aren’t even running?

Sounds like you wrote a bug… and that means… time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

Remember with Unity the code is only a tiny fraction of the problem space. Everything asset- and scene- wise must also be set up correctly to match the associated code and its assumptions.

1 Like

Just solved the problem. I removed Character Control component on the Object :blush: