Hello hello!
Currently revisiting one of my side projects, where I try getting as many objects as I may to be effected by body to body gravity, looking for suggestions on how I can further develop my code.
I’ve taken this from the wiki (which was a great learning tool and solid start):
http://wiki.unity3d.com/index.php?title=Gravity
Without double checking, I believe this script yielded around 20-30 objects before falling under 60fps. Refinement was a must. So, I chopped, I flipped, I re-wrote (is that a word?), then I broke a few times, then a few more…ended up with this:
public static List<GameObject> matter = new List<GameObject>();
void Update () {
//Gravity
List<Rigidbody> mRB = new List<Rigidbody>();
List<Vector3> mTP = new List<Vector3>();
foreach (GameObject gO in matter){
mRB.Add(gO.rigidbody);
mTP.Add(gO.transform.position);
}
for(int x = 0; x < matter.Count; x++){
for(int y = x + 1; y < matter.Count; y++){
Vector3 offset = mTP[x] - mTP[y];
if(offset != Vector3.zero){
Vector3 offsetCalc = offset / offset.sqrMagnitude;
mRB[y].AddForce (offsetCalc * (mRB[x].mass));
mRB[x].AddForce (offsetCalc * -mRB[y].mass);
}
}
}
//Spawn
StartCoroutine (FPS());
if(fps > minAllowedFPS && matter.Count < MaxSpawnCount){
StartCoroutine(Spawn());
}
}
On average, I’m getting anywhere from 160-220 spawns running at a continuous 60+ fps (thats with graphics and a crap more code that I haven’t included) …I’ll be honest I’m more often than not around 160…but hey, that’s a lot better than 30. Anyway, without getting into things such as octrees / quadtrees (because these are a bit to challenging at the moment, unless you know some crazy way to dumb it down I probably wont follow you), how can we improve on this?
Side note, I understand what oct/quad trees are doing…i Just don’t understand how they actually work. Have you looked at them? They’re magic. Probably black magic…