I have a sprite which has a transparent area in it. The non-transparent area is a free-form graphic (red). I would like to create a box collider around it (yellow), but ignoring the transparent area.
Some notes to the image above:
- Left: This is what happens, if I apply a
PolygonCollider2D
. The yellow line represents the area covered by thePolygonCollider2D
. This is not what I want. - Middle: This is what happens, if I apply a
BoxCollider2D
. The yellow line represents the area covered by theBoxCollider2D
. This is also not what I want, as it includes the transparent area of the sprite. - Right: This is what I want: Have a
BoxCollider2D
outside my free-form graphic.
Here's how I currently load my sprite data into the game during runtime:
My sprites are located in the
/Assets/Resources/SceneData/...
folder structure of my project. The graphics are stored as.png
files.When loading a level, I load the required graphics as sprites like this:
var sprite = Resources.Load<Sprite>("SceneData/AfternoonAtTheBeach/DragAndDrop/Graphics/Level1/ElephantWithIceCream");
"ElephantWithIceCream" is the .png
file (Resource.Load
wants me to refer to this file without file extension)
- After that, I create a new game object and attach a
SpriteRenderer
component to it. The sprite is assigned to theSpriteRenderer
by setting thesprite
attribute of theSpriteRenderer
component.
My first thought on how to solve my problem was to do something like this:
- Create a
PolygonCollider2D
and try to convert it into aBoxCollider2D
. But I was not able to find code examples on how to do this.
After that, I thought of trying it to do like this:
- Create a
PolygonCollider2D
and try to extract some useful information out of it (such as bounds, center, extents, etc...). - Delete the
PolygonCollider2D
and create aBoxCollider2D
. Use the previously extracted info to create theBoxCollider2D
.
But I fail doing so. I am also a bit confused as sometimes they refer to world space or local space. Does anyone have a working recipe for doing something like this? I do not really understand how to work with center, bounds and extents. If there is any better way of doing this, I am highly interested. Thanks a lot for your help!