I have been working on a simulation project for a while which involves N colliding balls in a 2D space. What I want to get is the count of the number of balls in each cell every frame and save it to a text file. A ball is said to be in a cell if more than 50% of the area of the ball is within the cell. How do I go about this?
PS: Each ball is an object of a pre defined class.
The correct way to do this is highly depending on your code. Can you share an MCVE sketch?
Ugh. Is this a requirement? Or could a ball be said to be in a cell if its center point is in the cell? This is a really weird definition for a grid of cells – for example, balls at the intersection points of the grid are 25% in each cell, so they are not in any cell!
If you go down this road, you may need to case each ball based on its points of intersection with grid lines, then compute the area of intersection.
The only good news here is that, if I’m understanding your use case right, then you can optimize like this:
Thank you for all of your replies.
I think I can do away with the 50% radius requirement. I really just need the number of balls in each cell every frame and the cell coordinates ie :
cell [(x,x+a);(y,y+a)] and count, where a is the side length of each square cell. I could just reference each cell by number, but then I have to generate the x,y values manually again anyway; since my ultimate goal is to get the spatial density of the balls for each frame.
I will be trying to implement this to processing as this seems to be the closest to what I need.
Since I am very new to this, I am sure I will muck it up somehow.
Thank you once again for all of your help. I will post here again, if I am stuck with the implementation ( which is inevitable).
You might like to look at https://codepen.io/scudly/pen/pPELKM for an example of a simple 2D gridded collision detector. ‘g’ toggles showing the grid. ‘r’ randomizes the ball locations. Up and down arrows change the ball sizes.
Each ball computes its grid number. Balls are sorted by grid number. Collisions are tested against balls in the same cell, one to the right, and three in the row below. It’s trivial to count the balls in each cell by just running down the list until you hit a ball with the next cell number.