# Get random position inside a 2D Polygon/CollisionPolygon

Pretty much title. How do I get a random position inside a given polygin to spawn something?

I think for a polygon, especially if itâ€™s potentially not convex, youâ€™re going to have to do some custom coding. If you were just using a CollisionShape then itâ€™s underlying Shape2D resource has a get_rect() method which returns a Rect2 object indicating its size; you could then just use randf to generate x and y values within that size to make a vector 2 and add it to the CollisionShapeâ€™s position.

But off the top of my head, I donâ€™t see a clean way to get something within a CollisionPolygon. Hereâ€™s one thought for custom code: If the position of the collisionpolygon is the center of the actual polygon shape and you also have a clean line from the center to any point on the boundary (such as when it is convex), then you can use that as an origin, and select a random angle from 0 to 2*pi. Then I think you could ray cast from that point with parameters set to raycast from inside allowed (which I think is a thing?) to find the distance to the edge. Then select a random number from 0 to that distance. Now you have a unique point in your shape given in polar coordinates (angle and distance from center). Use the polar to cartesian formula to get x,y coordinates relative to the position of the CollisionPolygon.

1 Like