Flying around and between planets

Hi peeps,

I’m trying to make my character fly around an object, like in this game:

Right now I have a semi-working script that involves planets with rotating transforms, and making the game character a child of one if it gets close enough. Trouble is, when I try to launch away from the planet, I go in the wrong direction.

Any idea how I might achieve this? I don’t think using real physics is a good idea, since this project is 2D.

Thanks in advance!

Interesting…yeah using F = Gm_1 * m_2 / r^2 and F = ma won’t work here, your best bet is to check when you are launching if the player is parented if not unparent and apply a force in the transform.forward position. This should propel it forward if the rotations are set properly. Then OnTriggerEnter2D you can have it parent to the current planet and have it orbit the given planet. Orbiting since you are just using a 2D environment you can use the elliptical equations for an ellipse and use that to “orbit” the object given a distance and a speed.

Hmmm… can’t seem to get that to work either. Closest I’ve come is using translate instead of applying rigidbody forces.

I wouldn’t use parenting. I’d keep track of the target transform, and then write a custom function to twirl around it.

This method, which I use frequently, would be perfect:

//Simply put 'this' in front of the first Vector2 argument to make it an Extension Method.
public static Vector2 PointOnCircle(Vector2 origin, float radius, float angle) {

      float x = radius * Mathf.Cos (angle * Mathf.Deg2Rad) + origin.x;
      float y = radius * Mathf.Sin (angle * Mathf.Deg2Rad) + origin.y;

      return new Vector2(x,y);
}

I whipped up a quick, crude example, of which the pertinent code is in the ships script:

    void FlyToAndAroundCurrentPlanet() {

        float heightFromSurface = currentPlanet.diameter * 0.5f + orbitHeight;

        //Pick a spot on an imaginary circle surrounding the planet, on orbitPhase angle around that circle
        Vector3 targetPosition = PointOnCircle (currentPlanet.transform.position, heightFromSurface, orbitPhase);

        //Lerp to that spot
        transform.position = Vector3.Lerp (transform.position, targetPosition, Time.deltaTime * 10f);

        //Increment the orbit phase to spin around it.
        orbitPhase += Time.deltaTime * orbitSpeed;


    }

Just import and run the ClickToOrbit scene. Click on any planet and your ship will fly to and around it.

1923958–124240–ClickOrbitExample.unitypackage (14.8 KB)

1 Like

You’re awesome doooood. Thanks!

Officer Doofy has yet again solved a case :slight_smile: