Prevent 2D Object from Leaving Screen

Hi,

So in my game, I’m prevent objects from leaving the screen by putting walls on each end of the screen. I’m using OnCollisionStay2D to check for when they the object has collided with the wall and fixing that object in place.

    void OnCollisionStay2D(Collision2D col)
    {
        switch (col.gameObject.name)
        {
            case "border_right":
                transform.position = new Vector2(col.gameObject.transform.position.x - col.gameObject.GetComponent<Collider2D>().bounds.size.x / 2 - GetComponent<Collider2D>().bounds.size.x / 2 - 1, transform.position.y);
                break;
            case "border_left":
                transform.position = new Vector2(col.gameObject.transform.position.x + col.gameObject.GetComponent<Collider2D>().bounds.size.x / 2 + GetComponent<Collider2D>().bounds.size.x / 2 + 1, transform.position.y);
                break;
            case "border_top":
                transform.position = new Vector2(transform.position.x, col.gameObject.transform.position.y - col.gameObject.GetComponent<Collider2D>().bounds.size.y / 2 - GetComponent<Collider2D>().bounds.size.y / 2 - 1);
                break;
            case "border_bottom":
                transform.position = new Vector2(transform.position.x, col.gameObject.transform.position.y + col.gameObject.GetComponent<Collider2D>().bounds.size.y / 2 + GetComponent<Collider2D>().bounds.size.y / 2 + 1);
                break;
            default:
                break;

        }
    }

The problem is that when I force it into its new position, it is still touching the wall, so it keeps getting called preventing it from leaving the wall. That’s why I added the +1’s and -1’s to the new positions so that it’s one pixel off from the wall. But now it studders when it tries to go past the wall and that’s a janky way of doing it anyways. Is there a better way to do this?

These objects are moving somehow — hopefully, because you’ve got a script that updates their transform.position on each frame, perhaps using some velocity vector.

So, your stay-in-bounds script needs to work with that one (perhaps even be the same script). When detecting a hit with a border, you should also check the velocity, and ignore it if the velocity is taking it away from the border. Otherwise, you should probably reverse the X or Y velocity, causing the object to bounce away.

1 Like

You can just limit the objects movement by just checking position and avoid colliders all together.

1 Like

Thanks for the reply! Is there anyway of doing that without constantly checking with Update? I’m using Rigidbody2d.velocity for the movement and the objects are kinematic.