Finding the center of mass on a 2D bitmap

前端 未结 3 1901
萌比男神i
萌比男神i 2020-12-31 13:54

I\'m coding a game, and I\'d like to be able to find the center of mass of an arbitrary shape on a black and white bitmap such as this:

 012345678
0.XX......
1..X         


        
3条回答
  •  没有蜡笔的小新
    2020-12-31 14:19

    You could count the number of adjoining cells, then center on the cells with the highest neighbor count.

     012345678
    0 XX      |
    1  XXX    |
    2   XXX   |
    3  XXXXXXX|
    4   XXX   |
    
     012345678
    0 23      |
    1  454    |
    2   775   |
    3  3686421|
    4   454   |
    

    In this example you could use the only cell with an 8, as the center point.

    If you came up with multiple cells with the same number of neighbors, you would just run the counting routine again, but this time just with the high number cells.

    For example, lets pretend that the cells that had 6, 7, and 8, instead all had eight neighbors.

     012345678
    0 23      |
    1  454    |
    2   885   |
    3  3888421|
    4   454   |
    
     012345678
    0 --      |
    1  ---    |
    2   XX-   |
    3  -XXX---|
    4   ---   |
    
     012345678
    0 --      |
    1  ---    |
    2   34-   |
    3  -342---|
    4   ---   |
    
     012345678
    0 --      |
    1  ---    |
    2   -X-   |
    3  --X----|
    4   ---   |
    

    In the case of a simple tie, I would go with the one that was nearer the center. In this case it would be the upper one of the two.

    Note: I'm assuming your not using this for an accurate physics simulation.

提交回复
热议问题