- Home /
Random Position Inside an object
Hi im attempting to create a method for getting a random location inside an object. Im mainly doing this to make my missiles a little more interesting as when dealing with a large object [1000 units] having lots of them all heading all to the same central point doesn't look good. I think I have a good basic method down but cant seam to get it to work;
//Position Generation Used in Start()
Transform c = target.FindChild ("ColSpheres");
if (c != null) {
int i = 0;
foreach (Transform s in c) {
i++;
}
Transform[] scd = new Transform[i];
i = 0;
foreach (Transform s in c) {
scd[i] = s;
i++;
}
int rands = Random.Range (0, i - 1);
Bounds b = (scd[rands].GetComponent (typeof(SphereCollider)) as SphereCollider).bounds;
targetpos = scd[rands].transform.localPosition
+ c.localPosition
+ Random.insideUnitSphere * b.extents.magnitude;
}
//Tracking Code used in Update()
Quaternion targetrotation = Quaternion.LookRotation (
(target.position
+ Vector3.Scale(target.transform.InverseTransformPoint (targetpos+target.position),
target.lossyScale)) - transform.position);
transform.rotation = Quaternion.RotateTowards (
transform.rotation, targetrotation,
turnspeeddeg * Time.deltaTime);
I think the main problem is located in the target rotation section as I cant seam to find the right method of transforming the local position to the world position.
Answer by Lord Simpson · Mar 30, 2011 at 09:56 AM
I Think I was over engineering the problem. The whole thing is simplified by using the spheres local position as the heading with a simple offset for random position within said sphere
//Start()
Transform c = target.FindChild ("ColSpheres");
if (c != null)
{
List<Transform> scd = new List<Transform>();
foreach (Transform s in c)
{
scd.Add(s);
}
int i = scd.Count;
int rands = Random.Range (0, i);
Bounds b = (scd[rands].GetComponent (typeof(SphereCollider)) as SphereCollider).bounds;
subtarget = scd[rands].transform;
targetpos = Random.insideUnitSphere * b.extents.magnitude;
Debug.Log((targetpos).ToString());
}
else
subtarget = target;
//Update()
Quaternion targetrotation = Quaternion.LookRotation ((subtarget.position + targetpos) - transform.position);
transform.rotation = Quaternion.RotateTowards (transform.rotation, targetrotation, turnspeeddeg * Time.deltaTime);