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.