Vincent Taylor

Create A Custom Ellipse In Unity, Part 1

As part of a side-project I’m currently doing, I need to calculate planetary orbits using Ellipses. Here’s how I’m doing it.

An ellipse of custom width, height, and segment number

Today’s Objective: Create a script to create custom ellipses used for planetary orbits.

Note: This post only creates a 2D ellipse. In one of my next posts, I will modify this to make it 3D as that is more suitable for planet orbits.

Creating the Ellipse shape:

Create a new MonoBehaviour script called “EllipseGenerator”.

Give it an Int variable for the number of segments in the ellipse (how smooth it is):

Give it 2 Float variables for the X and Y scale of the ellipse:

I’ve also made it require a Line Renderer to display the ellipse by giving it the following:

Finally, add a private Vector3 array to hold all the calculated points, and a public Vector3 array to allow other scripts to read the point array (not modify).

Now I will write the methods for the script:

To calculate the point position on the ellipse, I use the XScale and YScale plus the angle (0–360):

After the for loop, I add the code to make the Line Renderer show the ellipse in-game.

Then to make the ellipse modifiable at runtime, I add the OnValidate Unity method to recalculate the ellipse whenever the variables change:

As a last step, since the Line Renderer only shows when the game is playing, I add the OnDrawGizmos method to show a preview when in Edit mode.

Now to see the result:

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer since 8yo (18 years). Currently looking for games industry employment