Search code examples
pythonrandomsimulation

Getting a random position fixed distance from a point


I am trying to develop a solar system simulation.

To initialise the display, I need the planets to be randomly placed in their orbitals (fixed orbital radius) from the Sun. How do I get the random position?

I am using pygame for the display.


Solution

  • if a center of a circle is at (0,0) and radius is R, you can get the coordinates of a point on circumference using the formula x = R * cos(theta) y = R * sin(theta)

    python code will look like this:

    import random
    import math  
    
    R = 5  
    theta = random.uniform(0, 2 * math.pi)   
    x = R * math.cos(theta)
    y = R * math.sin(theta)