Dynamic Colliders, Releasing Pooled Objects (Unity)
Dynamically resizing box collliders to enclose the scene, so when pooled objects reach the limits can be released.
References
Table of Content
Dynamically Resize Colliders
- After initializing the boundaries of the scene, position and resize the box colliders.
- Enclose the play area with walls, these
BoxColliders
will belong to theProjectiles Limit
physics layer. - Using properties like
padding
andwall height
, we can control the shape of the enclosing.
1public BoxCollider top; 2public BoxCollider bottom; 3public BoxCollider left; 4public BoxCollider right; 5public float padding = 3.0f; 6public float wallHeight = 5.0f; 7public float wallThickness = 1.0f;
1public void Initialize(Boundaries boundaries) 2{ 3 var bottomLeft = boundaries.bottomLeft; 4 var topRight = boundaries.topRight; 5 6 // position 7 var centerX = 0; 8 var avgZ = (topRight.position.z + bottomLeft.position.z) / 2; 9 10 var topZ = topRight.position.z + padding; 11 var bottomZ = bottomLeft.position.z - padding; 12 13 var leftX = -topRight.position.x - padding; 14 var rightX = topRight.position.x + padding; 15 16 top.transform.position = new Vector3(centerX, 0, topZ); 17 bottom.transform.position = new Vector3(centerX, 0, bottomZ); 18 left.transform.position = new Vector3(leftX, 0, avgZ); 19 right.transform.position = new Vector3(rightX, 0, avgZ); 20 21 // size 22 var deltaX = (2 * topRight.position.x) + (2 * padding); 23 var deltaZ = topRight.position.z - bottomLeft.position.z + (2 * padding); 24 25 top.size = new Vector3(deltaX, wallHeight, wallThickness); 26 bottom.size = new Vector3(deltaX, wallHeight, wallThickness); 27 left.size = new Vector3(wallThickness, wallHeight, deltaZ); 28 right.size = new Vector3(wallThickness, wallHeight, deltaZ); 29}
Release Pooled Objects
- Make
Bullets
belong to thePlayer Projectiles
physics layer. - In the phyiscs collisions matrix, make sure to enable the interaction between
Player Projectiles
andProjectiles Limit
. - Define the
OnTriggerEnter()
message in the projectiles, and make them signal theirGun
to release the pooled object.
1public class Bullet : MonoBehaviour 2{ 3 public Gun gun; // this is set by the gun, when shooting 4 5 private void OnTriggerEnter(Collider other) 6 { 7 gun.ReclaimBullet(this); 8 } 9}
1public class Gun : MonoBehaviour 2{ 3 public void ReclaimBullet(Bullet bullet) 4 { 5 bulletsPool.Release(bullet); 6 } 7}