# 2D physics on game object made up of components

Say you want to let your users create a 2D airship (side view) made up of components. One component could be a floating balloon, another could be a storage room, etc.

And say you want this airship to have physics applied to it as a whole, with each component playing a part in this. For example, balloons would take away from its down force and other compartments would apply down force to it.

At the same time, the whole airship works as a whole (or at least the only physical separation would be between floater components and the others, which apply weight), so physics are applied to it as if it was one body.

Now, how can this be managed? How can I customize a game object via a script, giving it different components with different weights, and have it behave like it was a single premade object?

I'm sorry if the question is simple, but I'm only getting started with unity. Thank you very much!

TL;DR: Customizable airship gameobject with different components that have different weights. How to make it behave as a single physics entity and manage its different components?

One approach to handling the composite objects (collections of components that will move as a single object) would be:

Create a script to store the weight of a component.

    public class AirShipComponent : MonoBehaviour {
private float weight;
}


Create a script to total the weights of any child objects and apply the total to a Rigidbody.

    public class AirShipComposite : MonoBehaviour {

public new RigidBody2D rigidbody2d;

public void Awake() {
rigidbody2d = GetComponent<Rigidbody2D>();
}

public void UpdateTotalWeight(){
float totalWeight = 0f;
var childComponents = GetComponentsInChildren<AirShipComponent>();
foreach (AirShipComponent airShipComponent in childComponents) {
totalWeight += airShipComponent .weight;
}
rigidbody2d.mass = totalWeight;
}
}


Object hierarchy

Then place your GameObjects holding AirShipComponent as children of the GameObject with AirShipComposite and call UpdateTotalWeight(). You can then call UpdateTotalWeight() whenever the total should be updated.

• Thank you very much for your help! There isn't much info on this topic available online, and I'm just getting started with unity :) Can you provide some information on how to render the entire airship? Should each component render its own sprite, or should the container take care of that? – Marcos Pereira Apr 7 '15 at 18:07
• I would use one GameObject per sprite. It it keeps things simple and modular. As a bonus once you have the gameplay functioning the way you want, you should be able to animate them in a manner similar to the hero from the 2D Platformer demo project. – Kelly Thomas Apr 8 '15 at 10:21

i think one answer is in Distance Joint 2D : "The Distance Joint 2D component allows two Sprite objects controlled by rigidbody physics to be attached together to keep them a certain distance apart." Or Fixed Joint in unity 3d