Daniel
Daniel

Reputation: 691

Animate pygame sprite in elliptical path

This is pygame 1.9 on python 2.6..

Here is a screenshot of what is currently being drawn in my "game" to give some context. Here is the code.

It's supposed to be the moon orbiting around the earth (I'm not trying to make a real simulation or anything, I'm just using the setting to play around and learn pygame). It's 2 circles, and the moons elliptical orbit around the earth. My end game is to have the moon follow it's orbit around the earth, but I want to later use keyboard controls to adjust the shape of the moons orbit.

I really just need help with figuring out how to make the moon follow the path, I could probably figure the rest out.

Upvotes: 4

Views: 2099

Answers (1)

Claudiu
Claudiu

Reputation: 229321

Well here is how you generate points along an ellipse:

for degree in range(360):
    x = cos(degree * 2 * pi / 360) * radius * xToYratio
    y = sin(degree * 2 * pi / 360) * radius

(x,y) will follow an ellipse centered at (0,0), with the y radius being radius and the x radius being xToYratio. In your case, you probably want degree to be related to time passing somehow.

EDIT: you can also do this:

for degree in range(360):
    x = cos(degree * 2 * pi / 360) * xRadius
    y = sin(degree * 2 * pi / 360) * yRadius

where xRadius is half of your rect's width, and yRadius is half of your rects height. Visualize it intuitively - you have a circle, and you're stretching it out (i.e. scaling it, i.e. multiplying it) so that it's as big as the rect horizontally and vertically.

Upvotes: 5

Related Questions