[Tutor] Fwd: circular movement in pygame

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Apr 28 20:28:07 CEST 2015


On 28 April 2015 at 16:38, diliup gabadamudalige <diliupg at gmail.com> wrote:
>
> Looking at the code on this page lines 47 & 48
>
> http://programarcadegames.com/python_examples/show_file.php?file=sprite_circle_movement.py
>
> is there a way to do
> self.rect.x +*= some value*
> self.rect.y += some value
>
> rather than
>
> self.rect.x = self.radius * math.sin(self.angle) + self.center_x
> self.rect.y = self.radius * math.cos(self.angle) + self.center_y

There's no way to do that. The second version ignores the previous
value of self.rect.x/y.

I'm going to guess that the angle has only changed by a small amount
delta_angle between iterations in which case there would be a way to
do it approximately.

The real question is just why though? The second version is correct
and will be correct for ever. The first version would only be
approximately correct and over time you'd probably find that the
position would drift so that the ball was effectively at a different
radius.

In any case if
     x = r * sin(theta)
then
    dx/dt = r * cos(theta) * dtheta/dt.
Since
    y = r * cos(theta) that's
    dy/dt = x * dtheta/dt.
So you could update y approximately with:
    y += x * dtheta/dt * deltat
where deltat is your timestep. In your code that would be:
    self.rect.x += self.rect.y * self.speed
    self.rect.y -= self.rect.x * self.speed

Really what you have now is better though.


More information about the Tutor mailing list