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?