Planetary Orbits: Elliptical Animations with ActionScript

Planetary Orbits: Elliptical Animations with ActionScript

ast month I tried to encourage readers to embrace a couple of simple math concepts to expand the ol’ ActionScript skill set. I tried to show that by understanding some basic trigonometry (just sine and cosine, honest!) you could be wielding the power of the circle in no time. If you want to prime the pump for this month’s fun, you can check out last month’s article before continuing, but it’s not strictly necessary.

The idea behind my last article was to attempt to diminish the trepidation some users have about “using a lot of math” in scripting. I sometimes have the same problem, and I have to dig a little before I can get my head around a concept. So, I tried to create a handful of examples that build one upon the other, adding features in each new demonstration. One file, for instance, showed how to animate a MovieClip in a circle. Another example simply animated a second MovieClip around the first, while the first was moving in a circle of its own. The effect was a very primitive model crudely similar to the Moon orbiting around the Earth while the Earth orbited around the Sun.

Well, the story seems to have gotten the circle rolling in several regions of the world. One reader named Mike, from Japan, had this to say:

“I loved your article about animation using circles. You made the ideas so easy to understand it was like a light bulb was turned on over my head. The circle animating around another circle got me thinking about trying to mock up a mini solar system. But my first try didn’t look too good because planetary orbits are elliptical, not circular. Can you show me how to simulate a solar system using ellipses?”

Solar System Envy
Thanks for writing, Mike. Unfortunately, mocking up an accurate solar system is a little too complex for this forum. Beyond the elliptical paths around the Sun followed by many celestial bodies, there are other factors to consider. A few important examples are time, speed, acceleration, gravity, centripetal force, and more. Depending on the complexity of your model, you may also want to consider the effect that one celestial body has on another during their respective orbits.

However, I can at least discuss the basis of your question and talk about how to modify the simple code from last month’s article to accommodate elliptical paths. A simple application of an elliptical path should make the ellipse itself easier to grasp, and you can add complexity as needed.

Circle and Ellipse
I’ll try again to make this topic approachable to all, rather than concentrate too much on dense mathematical detail. If you are particularly interested in the latter, I’ve provided a few links in the Related Resources section (see left column) that will allow you to learn more about the geometrical nitty-gritty. Regardless, now is a good time to download the source code for this article so you can have the files handy when you need them.

It’s easy to understand a circle because of a few simple facts. A circle has an equal width and height more accurately called a diameter. Also, the distance from the center of a circle to its circumference (the boundary line you think of when you draw a circle) is the same for any point on that circumference. This is called the radius.

Figure 1. Shades of Round: A crude comparison of a circle and an ellipse are shown.

Purists will cringe (and I’ll get to more accurate descriptions in a moment) but, as a starting point, it may be helpful to think of an ellipse as an elongated circle with two unique radii?one for the x-axis and one for the y-axis (shown in the sample horizontal ellipse in Figure 1, that I will use throughout this article). In fact, a circle is an ellipse, but the two radii just happen to be equal. You’ll see how you can use that analogy by looking at the following code to animate on a circular path, from last month’s article:

function deg2rad(degree) {    return degree * (Math.PI / 180);}function animateCircle() {    var radian = deg2rad(this.angle);    this._x = this.centerX + this.radius * Math.cos(radian);    this._y = this.centerY + this.radius * Math.sin(radian);    this.angle += this.angleChange;    this.angle %= 360;}

The first function is just a utility routine that converts the degree angle unit that you are familiar with to radians, a unit that is more common in computer programming and required by Flash for all similar needs except the _rotation property.

The second function is the heart of the animation. It starts with a center point, which is the location on the stage for the circle, and a radius, which determines the size of the circle. It then derives the points on the circular path by taking the cosine of an angle for the x-coordinate, and the sine of the same angle for the y-coordinate. The function then updates the angle by an incremental value and starts the process over again when the 360-degree point is reached.

By sequentially supplying a series of familiar angle values?0, 10, 20, 30, etc., up to 360 degrees?the MovieClip will animate along the circular path. All of this is explained in greater detail in last month’s article, if you would like more information.

To change the above-coded circular path into an elliptical path with the same geographical center point, all you have to do is use a unique radius value for x and y. These can be derived from a familiar value simply by dividing the ellipse width and height by two, respectively). The example file “ellipse1_circle.fla” in the source code shows this clearly:

this._x = this.centerX + this.xRadius * Math.cos(radian);this._y = this.centerY + this.yRadius * Math.sin(radian);

That’s the only change required to get the first elliptical path from this code. “Sure,” you’re saying to yourself, “That’s fine for an elliptical path around the geographical center of the ellipse. But that doesn’t help with the basic simulation of a planetary orbit.” Right you are. For the next step, one must better understand how an ellipse is created.

Two Foci
The differing width and height of an ellipse that sets it apart from a circle means that there is not one center point that is equidistant from any point on the ellipse. Instead, an ellipse has two focus points. The distance to any point on the ellipse is the sum of the distance from each of these foci.

Figure 2. Two Foci: Creating an ellipse using two foci, “F1” and “F2.”

You can see this in practical terms by making an ellipse yourself. Put two thumbtacks about four inches apart in a paper-sized piece of cardboard. (These distances are arbitrary, but it will get you started.) Next, tie a loose-fitting string, about seven inches long or so, between the two thumbtacks. Finally, place a pencil inside the string and pull it away from the tacks until the string is taut. The string will look like a triangle with the pencil and the two tacks in the corners. Move the pencil all the way around the cardboard, keeping the string taut, and you will draw an ellipse.

This is illustrated in Figure 2. For the purposes of this article, “F1” will be the left focus point for a horizontal ellipse, or the top focus point for a vertical ellipse. Similarly, “F2” will be the right or bottom focus point, for horizontal or vertical ellipses, respectively.

Now that you’ve drawn your ellipse, you can move from arts and crafts to astronomy. In 1609, Johannes Kepler reasoned that the planetary orbits were not circular as once thought, but were elliptical with the Sun at one of the two focus points of the elliptical orbit. So, to simulate an orbit, you must be able to determine the location of the foci, and use one as the Sun.

Calculating the Foci
To calculate the focus points, you need to know a few basic things. Using correct terminology, the longest axis, going through the two focus points, is called the major axis. The axis perpendicular to this axis at the center of the ellipse is called the minor axis. Half the major axis, marked in Figure 2 by a, is called the semimajor axis. Half the minor axis, indicated as b in Figure 2, is called the semiminor axis.

Often, the first time learning a subject, it’s helpful to work with terms you are comfortable with. To simplify, I’ll use the terms “width” and “height,” and “xRadius” and “yRadius” when discussing the major, minor, semimajor, and semiminor axes, respectively. There’s still one more thing you have to figure out before you can continue.

To find the focus points of an ellipse, you must calculate the eccentricity of the ellipse. This is how elongated it is. Once you know the eccentricity of an ellipse, you can multiply this factor by the “xRadius” (or a in Figure 2) to get the distance from the center point to a focus point. This is marked by ae in Figure 2 and is the offset distance you’ll use in your script to move the ellipse to the correct new location.

There are a few ways to calculate the eccentricity of an ellipse. The formula I’ll use is:


(If you’re interested in knowing how this formula was derived, check out the Related Resources on ellipses, left column.) Writing that in ActionScript, using the aforementioned simplified terms, the formula becomes:

    e = Math.sqrt(1 - (yRadius*yRadius) / (xRadius*xRadius))

where Math.sqrt() is the Math object notation for square root.

Once you have the eccentricity of the ellipse, all you have to do is multiply that by the “xRadius” (in the case of our horizontal ellipse) to get the distance from the center of the ellipse to one of the focus points around which you can orbit your MovieClip. You may wish to orbit a MovieClip around a specific point, or it might even be the location of another MovieClip. For example, you might again want your example to show the Earth orbiting the Sun and the Moon orbiting the Earth.

But which focus point should you use? Since the ae (or xRadius * e) distance you just calculated is the same from the center to each focus point, the last step you need to take is to determine how to apply the offset. One method would be to use a conditional statement (if or switch, for example) to specify whether you add or subtract the offset from the center point of your ellipse. But there is a simpler way. If you use -1 to represent the left/top focus, 0 to represent the center, and 1 to represent the right/bottom focus, you can multiply the ae offset by this factor and subtract it from the desired anchor point.

For example, say you are placing your ellipse in the center of your stage at (275,200); you have an ellipse that is 250 pixels wide and 150 pixels tall. This results in an eccentricity of .8. Since your ellipse is 250 pixels wide, the “xRadius” is 125, or half the width. Therefore, the x offset would be calculated like this:

centerX -= (xRadius * e) * ellipseFocusPoint;

1) -1 for left focus point

    275 -= (125*.8) * -1       275 - (-100)

This adds 100 to the center point of the ellipse, making it appear as though it is orbiting around the left focus point.

2) 0 for center point

    275 -= (125*.8) * 0       275 - (0)

This does not change the center point of the ellipse.

3) 1 for right focus point

    275 -= (125*.8) * 1       275 - (100)

This subtracts 100 from the center point of the ellipse, making it appear as though it is orbiting around the right focus point.

The example file “ellipse2_foci.fla” in the source code makes this clear. It animates a MovieClip around the center of the stage, but shifts the ellipse by this ae factor allowing you to choose either the ellipse center, or either focus point as the point around which the object moves. It also stores the variables in the MovieClip object being animated (mc.xRadius, for example), making it possible to store different values for each MovieClip.

Author’s Note: Throughout, I’ve mentioned that I’m using a horizontal ellipse for this discussion. If you want to create a vertical ellipse, you must modify the equation slightly. First, you must switch around the major and minor axes in the calculation of the eccentricity of the ellipse. Remember that the eccentricity of the ellipse is how elongated it is. The equation must divide the shorter axis by the longer axis. If you accidentally invert these values, you’ll get a useless result because you’ll be trying to calculate the square root of a negative number.

For example, assume a vertical ellipse of 2 wide and 4 tall. The eccentricity formula would end up as the square root of 1 – 4/2, or 1-2, or -1. It helps to remember that an eccentricity of 0 is a circle, and an eccentricity of 1 is a straight line. Your e values will usually be between 0 and 1.

Similarly, you will want to shift the appropriate center coordinate based on whether or not the ellipse is horizontal or vertical. You don’t want to adjust the eccentricity formula for a vertical ellipse and then forget to change the y-coordinate instead of the x-coordinate.

The final adjustment to the two lines of ActionScript, for a vertical ellipse, would be:

e = Math.sqrt(1 - (xRadius*xRadius) / (yRadius*yRadius))centerY -= (yRadius * e) * ellipseFocusPoint;

Simulating Orbits … Finally
Again, considering the aforementioned very simplified model, the source code file “ellipse3_solar_sys.fla” shows how you can set up multiple orbiting bodies. This version of the code adds two things. First, it allows you to pick any spot around which to set up the ellipse. (The previous two examples used the center of the stage.) Second, it allows you to specify this value independently, for each orbiting body. So, for each MovieClip you can specify a point, or another MovieClip, around which to orbit.

To keep the script consistent, this is accomplished by passing either a MovieClip or a point object into the necessary parameter. For example:

setEllipse(mc3, 320, 220, 0, 2, -1, {_x:100, _y:200});setEllipse(mc2, 35, 30, 0, 10, -1, mc3);

The first line specifies that MovieClip “mc3” orbits point (100,200), while the second line specifies that MovieClip “mc2” orbits the current location of MovieClip “mc3″?wherever that may be. This allows you to set up a body that is orbiting another body that is in an orbit of its own (the Moon orbiting the Earth, which is orbiting the Sun). (To save your self a lot of frustration, be sure to read the sidebar, ” Know the Flash Execution Order.”)

What’s Next, Black Holes?
First and foremost, I hope you came away from this article with an understanding of how to modify a circular orbit into an elliptical orbit. If you think you can set up an elliptical orbit using its center, try using one of the ellipse’s focus points. As usual, I’d love to see any experiments that you may come up with!

devx-admin

devx-admin

Share the Post:
Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security.

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private,

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists

AI Tool

Unleashing AI Power with Microsoft 365 Copilot

Microsoft has recently unveiled the initial list of Australian clients who will benefit from Microsoft 365 (M365) Copilot through the exclusive invitation-only global Early Access Program. Prominent organizations participating in

Microsoft Egnyte Collaboration

Microsoft and Egnyte Collaboration

Microsoft has revealed a collaboration with Egnyte, a prominent platform for content cooperation and governance, with the goal of improving real-time collaboration features within Microsoft 365 and Microsoft Teams. This

Best Laptops

Top Programming Laptops of 2023

In 2023, many developers prioritize finding the best laptop for programming, whether at home, in the workplace, or on the go. A high-performing, portable, and user-friendly laptop could significantly influence

Renaissance Gaming Magic

AI Unleashes A Gaming Renaissance

In recent times, artificial intelligence has achieved remarkable progress, with resources like ChatGPT becoming more sophisticated and readily available. Pietro Schirano, the design lead at Brex, has explored the capabilities

New Apple Watch

The New Apple Watch Ultra 2 is Awesome

Apple is making waves in the smartwatch market with the introduction of the highly anticipated Apple Watch Ultra 2. This revolutionary device promises exceptional performance, robust design, and a myriad

Truth Unveiling

Unveiling Truths in Bowen’s SMR Controversy

Tony Wood from the Grattan Institute has voiced his concerns over Climate and Energy Minister Chris Bowen’s critique of the Coalition’s support for small modular nuclear reactors (SMRs). Wood points

Avoiding Crisis

Racing to Defy Looming Financial Crisis

Chinese property developer Country Garden is facing a liquidity challenge as it approaches a deadline to pay $15 million in interest associated with an offshore bond. With a 30-day grace

Open-Source Development

Open-Source Software Development is King

The increasingly digital world has led to the emergence of open-source software as a critical factor in modern software development, with more than 70% of the infrastructure, products, and services

Home Savings

Sensational Savings on Smart Home Security

For a limited time only, Amazon is offering massive discounts on a variety of intelligent home devices, including products from its Ring security range. Running until October 2 or while

Apple Unleashed

A Deep Dive into the iPhone 15 Pro Max

Apple recently unveiled its groundbreaking iPhone 15 Pro and iPhone 15 Pro Max models, featuring a revolutionary design, extraordinary display technology, and unrivaled performance. These new models are the first

Renewable Crypto Miners

Crypto Miners Embrace Renewable Energy?

As the cryptocurrency sector deals with the fallout from the FTX and Celsius exchange collapses, Bitcoin miners are increasingly exploring alternative energy sources to reduce expenses and maintain profitability. Specialists

Laptop Savings

The HP Omen 16 is a Gamer’s Dream

Best Buy is currently offering an unbeatable deal on the HP Omen 16 gaming laptop, giving potential buyers the chance to save a significant $720 on their purchase. Originally priced

How to Check for Vulnerabilities in Exchange Server

It is imperative to keep your systems and infrastructure up-to-date to mitigate security issues and loopholes, and to protect them against any known vulnerabilities and security risks. There are many