The platform is stuck and when you press the movement in the opposite direction you need to wait until it starts to move. How to remove this sticking? Swapping blocks of code did not help. Picture

Here is the code:

void Update(){ // горизонтальное движение playerPosition.x += Input.GetAxis ("Horizontal") * playerVelocity * Time.deltaTime; // обновление позиции платформы transform.position = playerPosition; // проверка выхода за границы if (playerPosition.x < -boundary) { transform.position = new Vector3 (-boundary, playerPosition.y, playerPosition.z); } if (playerPosition.x > boundary) { transform.position = new Vector3(boundary, playerPosition.y, playerPosition.z); } } 

    2 answers 2

    Maybe try differently?

    For example, it seems to me that it is easier to put colliders on the borders (left, right, top) and a platform to add a collider (well, of course, rigidbody2d ) and that's it. When colliding with the collider, the platform itself will no longer be able to move, so there will be no need to do extra work. Those. will be just

     void FixedUpdate () { float h = Input.GetAxisRaw("Horizontal"); GetComponent<Rigidbody2D>().velocity = Vector2.right * h * playerVelocity; } 

    Another option, this:

    Suppose you know the width of the field and just want to limit movement by + -8 units. Then you can simply limit the movement of the platform using Mathf.Clamp , which does not allow you to take a value less than the specified minimum and greater than the specified maximum, ie:

     void Update() { float xPos = transform.position.x + (Input.GetAxis("Horizontal") * playerVelocity); playerPosition = new Vector3(Mathf.Clamp(xPos, -8f, 8f), -9.5f, 0f); transform.position = playerPosition; } 

    Here we just say - move along the X coordinate, but not less than -8 and not more than +8;


    In general, playerPosition.x seems to be located in the center of the object, if memory serves me so you need to at least check

     playerPosition.x - player.width/2 <= леваяГраница 

    and

     playerPosition.x + player.width/2 >= праваяГраница` 

    so maybe this is the reason.

      I corrected by adding the Rigidbody2D platform, put the walls on the sides and prescribed another movement.

       void FixedUpdate(){ float move = Input.GetAxis("Horizontal"); GetComponent<Rigidbody2D>().velocity = new Vector2(move * maxSpeed, GetComponent<Rigidbody2D>().velocity.y); }