- Home /
Calculate objects' mass based on density and volume
Hello, I'm trying to calculate objects' masses based on density and volume.
Imagine I have a Box2DSprite and it is 1,1 (x,y), I could use mass=density*Box2D.localScale.x*Box2D.localScale.y and calculate it.
I want to order the boxes in a GameObject called Boxes and then they are parents. I want to calculate each box weight/mass individually based on the formula and then apply to the objects!
How could I do this?
Code in JS:
#pragma strict
var Density:float=1000;
function Start(){
var Rigidbodies=gameObject.GetComponentsInChildren(Rigidbody2D);
var Transforms=gameObject.GetComponentsInChildren(Transform);
for (var Tfm : Transform in Transforms)
for (var Rb : Rigidbody2D in Rigidbodies)
Rb.mass=Density*Tfm.localScale.x*Tfm.localScale.y;
}
Please state the problem, and pay careful attention to how you phrase your posts. I do not understand the issue. Be very specific about what assistance you require. How to access the children on a transform? How to run your formula on each child and sum the results?
Answer by siaran · Mar 15, 2015 at 04:55 PM
I think I see your problem. You're looping through each transform, and at each transform you are looping through every rigidbody and settting all rigidbodies with whatever mass you calculated for that rigidbody, so they will all end up with whatever you calculated for the last one.
Instead, try something like this (not good at javascript sorry for errors)
//all child transforms
var children = gameObject.GetComponentsInChildren(Transform);
for (var child : Transform in children){
float calculatedMass = child.localScale.x*child.localScale.y*density;
//not sure you can get a rigidbody from transform like that.
//otherwise I guess child.gameObject.rigidbody is the way to access it?
Rigidbody body = child.rigidbody;
if(body) body.mass = calculatedMass;
else Debug.LogError("This object has no rigidbody on it!");
}
Your answer
Follow this Question
Related Questions
How is Rigidbody 2D Auto Mass calculated? 2 Answers
How to give dynamically add mass to a gameobject from volume(collider.bounds.size) and density 1 Answer
Can I make mass and density constant independent of Collider 2D size? 1 Answer
Calculating rigidbody mass 1 Answer
Can't change Rigidbody2D mass 1 Answer