Search code examples
pythonpathpygamegame-physics

automated semi-circular path movement with pygame


I'm trying to create a traffic simulator using python (+ pygame and math libs).

I'm stuck at car movements, I've managed to create a fixed horizontal and vertical path using a list of coordinates, using nested for loops.

Now, since I'm in a crossroads I now have to make the 1/4 of a circle to make a left or right turn.

The car has to make a straight path for n pixels (and it's ok) then have to make the 1/4 following a circular path and then proceed towards a straight line again.

I have a list of coordinates, however, I don't know how to make it turn around the center of the circumference (which I know the coordinates of) while also turning the image relative to the center!

I'll give you an idea of the problem using an image The red paths "1" are done, the problem is the blue tract "2", "O" coordinates are known, there are 4 "O" in total (one for each path).


Solution

  • I would suggest to use the equation of a circle which is (x – h)^2 + (y – k)^2 = r^2 where (h,k) are the coordinates of the cercle's center and r the radius. The idea in your case could be to draw all discrete points (x,y) that verify this equation, here is an example (for points where x and y are positive regarding the origin, if we follow your example):

    import numpy as np
    import matplotlib.pyplot as plt
    center = (10,10)
    radius = 5
    th = 0.01
    for x in np.arange(center[0],center[0]+radius+th, th):
        for y in np.arange(center[1], center[1]+radius+th, th):
            if abs((x-center[0])**2 +  (y-center[1])**2 - radius**2) < th:
                plt.scatter(x,y)
    plt.show()
    

    You can then control the number of points with the th, and even draw lines instead of just points to speed up the process