Limit player movement on X

Im working on my first game that i need dodge obstacles with my car and i want to block the way out of the road so i wanted to limit his X position to make he only possoble of moving between -2.8 and 2.8.

here is my movement code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class player : MonoBehaviour
{

    public float velocidade;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        movimentação();

    }
    void movimentação()
    {
        if (Input.GetKey(KeyCode.D))
        {
                transform.Translate(velocidade * Time.deltaTime, 0, 0);
        }
          
        if (Input.GetKey(KeyCode.A))
        {
            transform.Translate(-velocidade * Time.deltaTime, 0, 0);
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.Translate(-velocidade * Time.deltaTime, 0, 0);
        }
        if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.Translate(velocidade * Time.deltaTime, 0, 0);
        }
    }
    void OnTriggerEnter2D(){
       
        Debug.Log ("Bateu");
   
   
   
   
   
    }

}

add this to your Update / movimentação:

transform.position = new Vector3(Mathf.Clamp(transform.position.x, -2.8f, 2.8f), transform.position.y, transform.position.z);
5 Likes
    public class player : MonoBehaviour
    {
        public float velocidade;

        void Update()
        {
            movimentação();
        }

        void movimentação()
        {
            // set the float values to +/- 1 if the keys are down pressed
            float inputLeft = Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow) ? -1 : 0;
            float inputRight = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow) ? 1 : 0;
           
            // put the values into a vector and clamp the X to -2.8 and 2.8
            Vector3 input = new Vector3(Mathf.Clamp((inputLeft + inputRight) * velocidade * Time.deltaTime, -2.8f, 2.8f), 0, 0);

            // translate by the new vector
            transform.Translate(input);
        }

        void OnTriggerEnter2D(Collider2D other)
        {
            Debug.Log("Bateu");
        }
    }

You could do something like this.

thank you bro you save my time :heart: