Physics.OverlapSphere not working
Hi Everyone. I am creating a code that generates spheres that are 5 distance from the previous one in a random direction - which works . I am trying to get it so that it is at least 4.5 distance from all other spheres. The spheres have a sphere collider on them and I am using Physics.OverlapSphere to calculate the number of spheres at the location of the last placed sphere. I should always get at least 1 (i.e. the last placed sphere), if it is greater than one, I transform the position and try again. However, PhysicsOverlapSphere counts 0 mostly (2 for the starting few for some reason). if I do not transform the position once placed, even more bizarrely, the number is equal to the number of spheres in total (i.e. the OverlapSphere is acting as if it is massive). I am also instantiating cubes in between, but I took the code out and the problem still persisted, so I think I can rule that out. Any help would be much appreciated:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class SkillTree : MonoBehaviour { public GameObject node; public int[] posnegrand; public Vector3 nodelocation; public GameObject currentnode; public GameObject currentline; public GameObject lastnode; public GameObject cylinder; public Collider[] collider1; public float xrandom; public float yrandom; public float zrandom; public float y2z2; // Start is called before the first frame update void Start() { for(int i=0; i<500;i++) { if (i==0) { nodelocation = new Vector3(0,0,0); } else {nodelocation = currentnode.transform.position;}
Instantiate(node,new Vector3(0,0,0), Quaternion.identity);
Instantiate(cylinder,new Vector3(0,0,0), Quaternion.identity);
currentnode=GameObject.Find ("Node(Clone)");
currentline =GameObject.Find ("Line(Clone)");
currentnode.name="Node"+i;
currentline.name="Line"+i;
for (int j=0; j<1;j++)
{
xrandom = Random.Range(0f,5f);
y2z2 = 25 - (xrandom*xrandom);
yrandom = Random.Range(0,Mathf.Sqrt(y2z2));
zrandom = Mathf.Sqrt(y2z2-(yrandom*yrandom));
for (int k=0;k<3;k++)
{
posnegrand[k] = Random.Range(0,2);
if (posnegrand[k] == 0)
{posnegrand[k] = 1;}
else if (posnegrand[k] == 1)
{posnegrand[k]=-1;}
}
currentnode.transform.position = new Vector3(nodelocation.x + xrandom*posnegrand[0],nodelocation.y + yrandom*posnegrand[1],nodelocation.z + zrandom*posnegrand[2]);
currentline.transform.position = new Vector3((nodelocation.x+currentnode.transform.position.x)/2,(nodelocation.y+currentnode.transform.position.y)/2,(nodelocation.z+currentnode.transform.position.z)/2);
currentline.transform.LookAt(currentnode.transform.position);
collider1=Physics.OverlapSphere(currentnode.transform.position,4.5f);
Debug.Log(collider1.Length);
if (collider1.Length>1)
{j=-1;}
}
}
}
// Update is called once per frame
void Update()
{
}
}
Your answer