- Home /
JS access spherecast position
In this 2d concept im trying to make a bacteria colony produce spores. So i make it look in a random direction around itself and if it casts a sphere in that direction without hitting any other spores, then it grows a spore there. But, im not sure how to re-access the spherecast's position once iv used it. here is my code:
#pragma strict
var growthCount = 0;
var growthCountMax: int;
var newSpore: GameObject;
var randomDir: Vector3;
var hit: RaycastHit;
var spawnDistMaster: float;
var spawnDist: float;
var spawnDistNoise: float;
var newSporePos: Vector3;
function Start ()
{
}
function Update ()
{
}
function incGrowthCount(num:int)
{
growthCount = num-1;
}
function lookForGrowSpot()
{
spawnDist = spawnDistMaster + Random.Range(-spawnDistNoise, spawnDistNoise);
randomDir = Vector3(Random.Range(-359,359),0,Random.Range(-359,359));
Debug.DrawRay(transform.position, randomDir, Color.cyan);
if(!Physics.SphereCast(transform.position, .3, randomDir, hit, spawnDist))
{
Debug.Log("Hit Nothing");
//store the spherecasts ending position in "newSporePos"
//newSporePos = ?;
grow();
return true;
}
Debug.Log("hit somthing");
return false;
}
function grow()
{
//make spore at newSporePos
}
also as a bonus question: is there a better way to make a random direction in 2d than what i did? what i have now just feels wrong.
Answer by aldonaletto · Aug 30, 2013 at 01:14 AM
The last will be first: you can generate a vector pointing in a random direction inside the plane XZ with a code like this:
randomDir = Quaternion.Euler(0, Random.Range(0, 360), 0) * Vector3.forward;
It generates a random rotation from 0 to 359 and applies it to a unit vector that originally pointed in the Z axis direction.
About the SphereCast: you should calculate the position by adding the random direction vector to the origin - but make sure that the vector length is equal to the distance to the new spore - it will be easy if randomDir is generated like above, because it has unit length: just multiply it by the desired distance. The code could be like this:
...
function lookForGrowSpot()
{
// generate unit vector pointing in a random direction:
randomDir = Quaternion.Euler(0, Random.Range(0, 360), 0) * Vector3.forward;
Debug.DrawRay(transform.position, randomDir, Color.cyan);
// if position free...
if(!Physics.SphereCast(transform.position, .3, randomDir, hit, spawnDist))
{ // calculate the position:
newSporePos = transform.position + spawnDist * randomDir;
grow();
return true;
}
return false;
}
NOTE: The spores must have colliders in order to be detected by SphereCast.