How to auto adjust the collider to the sprites size.
When designing a 2D level we usually need to resize our sprites to match the design and the difficulty level that we want to have. Also we need to be able to adjust it based on the feedback from the players:
The setup:
Ok now we can adjust the size as we want. But is the sprites size the only concern?
Problem with the collider
The problem is that the sprite needs to have a collider so that our agents can use them. Also the collider needs to be adjusted to the sprite to avoid some strange bugs in our game.
Lucky for us we can ensure that all colliders adjust their size dynamically at the start of the game. All we need is a script attached to our platform ex PlatformColliderAdjustment.cs :
public class PlatformColliderAdjustment : MonoBehaviour { [SerializeField] private BoxCollider2D platformCollider; [SerializeField] private SpriteRenderer spriteRenderer; private void Start() { platformCollider.size = new Vector2(spriteRenderer.size.x, platformCollider.size.y); } }
All we need to do is to set the size of the collider to a new Vector2. In my case I only worry about X axis its using the size of the spriteRenderer.size.x while Y axis stays the same (platformCollider.size.y).
Keep in mind that most child classes of Collider2D has the size parameter, but the base class has only Bounds struct assigned to it.
Want to learn more about Unity 2D?
The above solution is from my video course about making a 2D platformer game in Unity 2020. If you want to learn more about making 2D games and at the same time help me to make more free learning materials check it out here: Make a 2D platformer using Design patterns
PS. Here is the code that I use to display a gizmo over the collider:
public class ColliderGizmo : MonoBehaviour { public BoxCollider2D colliderbox; public Color gizmoColor = Color.green; private void OnDrawGizmos() { if (colliderbox == null) return; Gizmos.color = gizmoColor; Gizmos.DrawCube(colliderbox.bounds.center, colliderbox.bounds.size); } }
You can also check my other tutorials on my YT channel:
If you agree or disagree let me know by joining the Sunny Valley Studio discord channel :)
Thanks for reading!
Peter