- Home /
Question by
jimpy · Jul 24, 2020 at 12:43 PM ·
2d gametop down shooterborder
2D top down shooter border.
Is their a way to have a world border without having to make 4 rectangles and just having one big box where the player can move in?
Comment
Answer by Essexrookie · Jul 24, 2020 at 02:47 PM
If I understand your question right here's 2 different methods that works for me
1: Clamps your sprite in screen bounds
void Update(){
//Using world space calculations
//Get limits using viewport positions
Vector3 leftBottom = cam.ViewportToWorldPoint(Vector3.zero);
Vector3 rightTop = cam.ViewportToWorldPoint(new Vector3(1, 1, 0));
float leftLimit = leftBottom.x;
float botLimit = leftBottom.y;
float rightLimit = rightTop.x;
float topLimit = rightTop.y;
Vector3 extents = sprRnd.bounds.extents;
//Clamp with sprite extends offset added
Vector3 pos = transform.position;
pos.x = Mathf.Clamp(pos.x, leftLimit + extents.x, rightLimit - extents.x);
pos.y = Mathf.Clamp(pos.y, botLimit + extents.y, topLimit - extents.y);
transform.position = pos;*/
}
2: Border With Box Colliders
public BoxCollider2D right, left, top, bottom;
void Update ()
{
right.size = new Vector2(1f, Camera.main.ScreenToWorldPoint(new Vector3(0f, Screen.height * 2f, 0f)).y);
right.offset = new Vector2(Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0f, 0f)).x + 0.5f, 0f);
left.size = new Vector2(1f, Camera.main.ScreenToWorldPoint(new Vector3(0f, Screen.height * 2f, 0f)).y);
left.offset = new Vector2(Camera.main.ScreenToWorldPoint(new Vector3(0f, 0f, 0f)).x - 0.5f, 0f);
top.size = new Vector2(Camera.main.ScreenToWorldPoint(new Vector3(Screen.width * 2f, 0f, 0f)).x, 1f);
top.offset = new Vector2(0f, Camera.main.ScreenToWorldPoint(new Vector3(0f, Screen.height, 0f)).y + 0.5f);
bottom.size = new Vector2(Camera.main.ScreenToWorldPoint(new Vector3(Screen.width * 2f, 0f, 0f)).x, 1f);
bottom.offset = new Vector2(0f, Camera.main.ScreenToWorldPoint(new Vector3(0f, 0f, 0f)).y - 0.5f);
}
}
In the first method in the 10th line, is "sprRnd" the gameobject or what is it?