Provided files:
You will be creating the following animated planet and moon simulation:
The moons (white) have a gravitational force applied to them which causes them to circle the planet (red). We are providing you with the file GravityMain.as
with some skeleton code. You must modify GravityMain.as
and additionally write a new class, Moon.as
. GravityMain.as
is the document class for the program.
The Moon class represents a single moon which can orbit around the center planet. The planet should have an x and y velocity associated with it. It has the following methods:
Moon():void
This function should use the Moon's graphics object to draw the moon. The moon should be a white (0xFFFFFF) circle with a radius of 10 pixels. The circle should be oriented around the center of the Sprite.
update():void
This function should update the moon's x and y position based on the moon's current x and y velocity. Each call to this method should update the moon once; there need not be a for loop or event handlers associated with this function.
The following functions have already been written for you in the GravityMain.as
file, but you must make some modifications to them:
GravityMain():void
Initially, the constructor calls drawPlanet() to draw a planet in the center of the stage. You must add code to the constructor to add the "enter frame" event listener. You can also add code to help initialize your simulation (i.e. add moons to the stage). Remember, this constructor is like the main method in Java. It is the first code run in your .swf movie.
To set up the simulation, you should create 10 moons at random (x, y) coordinates spread evenly across the stage. Each Moon should be given a random initial x and y velocity between -5 and 5.
drawPlanet():void
You do not need to modify this function in any way.
onEnterFrame(e:Event):void
You must add code to this function which updates the simulation on every frame. This will involve calling the update() method for each of your moons and gravitating each moon to the planet.
gravitate(m:Moon, tx:Number, ty:Number):void
This is the most difficult function to implement. It accepts a moon object and target x and y coordinates and applies a gravitational force to the moon object as if it were being pulled to the target x and y.
Here is an overall summary of the algorithm:
Recall from high school physics that the force of gravity can be calculated with the following formula:
We will be simplifying this formula. In particular, we will not worry about the masses of the two objects:
Finally, we will also not being squaring the distance between the two objects:
Furthermore, we will not be using the real gravitational constant G. Instead, we will allow you to choose your own value for G. Different G's will have different effects on the simulation. Experiment!