Megabite #20 - Moving Platform with Movable Player (by request)

This Megabite, the 20th in the series, will focus on a question asked by a reader.  D Hunter asks:

... I’d love to know how to script a player-controlled ship you can walk around while it’s moving (like on autopilot). I’ve been struggling with this and it’s hard to find resources on that particular issue. If you can find a way to generalize it to the principal, that would be sweet too; if its not in your interest, no worries either :) I’m still pretty new to Unity

Well, D Hunter, I'm happy to say that this will be an easy one for you - assuming your autopilot is already functional.  What we're going to do here is set up a rigidbody for the "ship", switch it to isKinematic = true, and add some constraints for the demo.

For my ship, I just made a cube.  I added a rigidbody component like so:

Take note of the constraints - We don't want it flipping around for any reason, and we don't want it being affected by gravity to fall into the planet.  For motion, I simply added a RotateAround .js file, but if yours uses AddForce or ConstantForce, that should work just as well.

function Update () {
transform.RotateAround(Vector3.zero, Vector3.up, 10 * Time.deltaTime);
}

It's rotating around the vector of 0,0,0.  When I added my standard character controller, I made sure to add it as a CHILD of the ship itself, so it rotates along with the parent.  Input and movement are now relative to the parent.  Which means you don't want to simply jump off of the ship and hit the ground - the character, if attached as a child, would continue to move with the ship.  If you wanted something like that, you would need to have something added to set the parent to null given a certain scenario.

Because of this, I added some invisible walls to make sure the character stays on the ship at all times.  The collision detection isn't as strong as it should be, so if you were to jump against them a few times your character will fall from the ship and you can see how bad that could get :)

Of course, you want to make sure those walls are children of that parent ship as well.  They will all move together that way and everything runs smooth.  Below, I'll add the demonstration scene and a download link for the package itself so it might help anyone else struggling with this issue

Use WSAD controls to move around :)


Download Package