To make the algorithm work, you have to operate with floating point numbers. If m
and p
are pygame.Rect
objects, then the algorithm won't work, pygame.Rect
operates with integral numbers and the fraction part gets lost.
Note math.sin(angle_radians)
and math.cos(angle_radians)
is <= 1.
That means you have to store the positions of the objects in separate variables. Let's assume you have the floating point coordinates (mx
, my
) and (py
, py
)
You have to find the Unit vector from (mx
, my
) to (px
, py
).
The unit vector can be found by dividing the vector from (mx
, m.y
) to (px
, py
) by its length.
The length of a vector can be computed by the Euclidean distance.
Finally multiply the vector by a scale (step
) that is not greater than the distance between the points and add it to the position. e.g:
stepDist = 1
# vector from (`mx`, `my`) to (`px`, `py`)
dx, dy = p.y - mx, py - px
# [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance)
len = math.sqrt(dx*dx + dy*dy)
if len > 0:
# [Unit vector](https://en.wikipedia.org/wiki/Unit_vector)
ndx, ndy = dx/len, dy/len
# minimum of step size and distance to target
step = min(len, stepDist)
# step forward
px += ndx * step
py += ndy * step
If a pygame.Rect
object is of need, then the position of the rectangle can be set. e.g:
m.topleft = round(mx), round(my)
p.topleft = round(px), round(py)
But not you have to store the positions in (mx
, my
) respectively (px
, py
). If you would do mx, my = m.topleft
respectively px, py = p.topleft
, then the algorithm will break down, because the fraction component gets lost.