Search Unity

[Question] Box collider surrounding a list of sprites

Discussion in '2D' started by NMatanski, Jan 17, 2020.

  1. NMatanski

    NMatanski

    Joined:
    Jul 2, 2019
    Posts:
    6
    How to surround a list of SpriteMesh with a BoxCollider2D? I have an array of objects that have SpriteMeshInstance components. So I've got all sprite meshes from the sprite mesh instances and then the sprites from the sprite meshes. What now? I have a list of sprites and I need to surround them with a box collider. I think that I need to use their bounds.size and bounds.center, but I don't know how to calculate the final size and offset of the BoxCollider2D.

    TL;DR:
    List<Sprite> sprites; BoxCollider2D boxCollider
    I need to change the size and offset of the boxCollider so as to fit all of the sprites in the list. Please, share a code solution, even if it's not the most effective and precise algorithm, it will make me happy.

     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,474
    Sorry but I don't have a code solution to share but if you have all the sprite vertices then you will also need to know the Transforms on the GameObject that the Sprite is being used (presumably by a SpriteRenderer). You can then iterate all the sprites/vertices transforming the vertices into world-space. You transform into world-space by using the Transform using Transform.Point.

    Iterating all these sprites and their vertices you can then calculate the following as you do so:
    • Find the Minimum Vertex in XY
    • Find the Maximum Vertex in XY
    • Vertex Sum (simply add them all up)
    When you have the Vertex Sum you can divide it by the total number of Vertex you iterated. This will give you an average position of all vertices i.e. the average center and that is where the BoxCollider2D needs to be placed. For the Width/Height of the BoxCollider2D, you can use Maximum Vertex XY - Minimum Vertex XY.
     
    Last edited: Jan 17, 2020
    NMatanski likes this.