How to change transform.position.x to go backwards at specific instance?

Hi,

I’m having some trouble with moving my character. I’m trying to get it to go in the negative x direction when the character passes a certain x position. Any help?

public class Movement : MonoBehaviour {

public float moveSpeed;
// Use this for initialization
void Start () {
	moveSpeed = 0.8f;
}

// Update is called once per frame
void Update () {
	transform.position += new Vector3(.0001f, 0, 0);

	if ((transform.position.x) > 0.005 && transform.position.x < .01) {
		transform.position -= new Vector3(.0001f, 0, 0);
	}

}

}

Hello @miwwes.

The problem with your code is that you’re telling the object to move right and after that you’re immediately telling it to go left. That’s is why it seems stuck at 0.0049. You can fix this by manipulating the situation and changing the if statement.

Try changing your code to something like this:

public float moveSpeed;

private bool moveRight = true;

void Start()
{
    moveSpeed = 0.8f;
}

void Update()
{
    if (moveRight == true)
    {
        transform.position += new Vector3(0.0001f, 0, 0);

        if ((transform.position.x) >= 0.01f)
        {
            moveRight = false;
        }
    }
    else
    {
        transform.position -= new Vector3(0.0001f, 0, 0);

        if ((transform.position.x) <= 0)
        {
            moveRight = true;
        }
    }
}

Let me know how it goes and all the best :slight_smile:

If you want to access a particular axis in any transform component you can always reference it separately.

you can do it like this:

 public float moveSpeed;
 // Use this for initialization
 void Start () {
     moveSpeed = 0.8f;
 }
 
 // Update is called once per frame
 void Update () {

     transform.position.x += 0.0001f;

     if ((transform.position.x) > 0.005f && transform.position.x < 0.01f) {
         transform.position.x -= 0.0001f;
     }
 }