(I intend to add a YouTube walk-though before the end of August)
Docking a spaceship creates an interesting game development issue in Unity + Gravity Engine scenes. The updates to the ship transform are being handled by Gravity Engine and this prevents the use of all the rigidbody physics provided by Unity for rotation, translation and collision physics. The Docking demonstration scene provides and example of how to get the best of both systems in a scene. The central idea is: create a ship with a rigidbody component and make it a child of the spaceship NBody object. Gravity engine will continue to update the parent location ensuring correct orbital motion and the Unity physics system will manage the small motions of the ship with respect to the NBody parent.
This approach assumes that the local position from the parent NBody will be small compared to the radius of the orbit. If it grows large then motion will not correctly reflect the orbit at that location.
There are two approaches that can be used in a hybrid Nbody/Rigidbody scene:
- Examine the local position and velocity of the rigidbody child every FixedUpdate and adjust the Nbody position/velocity (zeroing out the rigidbody position and velocity every FixedUpdate)
- Allow local motion within a specified radius of the NBody and update the NBody when this radius is exceeded.
In the docking scene option (2) is used with a modification. To model the encounter of two objects and allow rigidbody physics between them they are both made children of a new NBody object that represents the center of mass of the two nbodies. The logic is:
- When the ships are within the “docking radius” create a new NBody for the center of mass (CM) and make the rigidbody children of the original nbodies children of the CM NBody.
- Inactivate the original nbodies.
- If the ships exceed the “docking radius” revert back to the original configuration and zero the local position and velocity with respect to their NBody parents.
This logic is implemented in the DockingGroup script.
Once the ships are within the docking radius then all the usual rigidbody physics can be used to control the rotation and translation of the ship and the docking target. The ReactionControlSystem script in the docking scene provides a simple keyboard controller to translate and rotate the ship. Colliders on the ship and the station with the usual physics materials handle cases where the ship and station make contact.
The final logic needed is to detect when docking has occurred. The DockingPort script is added as a separate child object to the spaceship model and the station model. This is a simple position/orientation/velocity bounds checked to determine when to declare the ship docked.
When docking is achieved there is additional logic to treat the objects as a single NBody.