- Home /
spherecast wont work
var enemyNearing: RaycastHit;
var start : Vector3 = transform.position;
if (Physics.SphereCast(start, view, transform.forward, enemyNearing, 0.000001) && enemyNearing.transform.tag == "EnemyUnit")
{
enemyNear = true;
target = enemyNearing.collider.gameObject.transform.position;
}
else
{
enemyNear = false;
}
This is my code that i am using for the spherecast but for some reason enemyNear isnt becoming true. It seems as though the raycast isnt even firing. How can i fix this?
This looks odd
var start : Vector3 = transform.position;
why do that only to turn around and use start as 1st parameter; why not transform.position (or a true cached of Transform)
What is view, there's no definition shown here? Why is the sweep distance so tiny?
i like to keep things clean and simple and having a variable in the parameters helps do that. View is just a simple float that changes based on the type of unit, in this case it is 50. The sweep distance is tiny because i don't want the ray to move forward i want it to stay relatively right on top of the object casting it.
Assu$$anonymous$$g your tag is correct, the issue is SphereCast so you just need to evaluate those parameters. Is the origin perhaps inside a collider? And the enemy has true Colliders (not isTrigger checked)?
You should get rid of transform.forward and make that a parameter too eh?
Answer by CatchCo · Mar 31, 2014 at 11:28 PM
So the reason this is not working is because SphereCast doesn't work how you think it does. Spherecast will ignore any colliders that it touches at it's starting point. It's meant to detect objects as it moves.
If you want to detect nearby colliders manually you should look into Physics.OverlapSphere. It does not require movement and will detect collisions as you are aiming to do here.
i tried overlapSphere but i dont get it at all. I spent hours looking and couldnt figure out how i am supposed to define the parameters and only return true the tag that I want.
Here is how you would do that: (assu$$anonymous$$g you are using javascript)
function EnemyIsNear() : bool
{
var hitColliders = Physics.OverlapSphere(transform.position, view);
// search through all hit colliders for an enemy
for (var i = 0; i < hitColliders.Length; i++)
{
if (hitCollider.tag == "EnemyUnit")
{
return true; // we found an enemy. exit early
}
}
return false; // looked through all hit colliders but none was an enemy
}
it says if (hitCollider.tag == "EnemyUnit") { return true; // we found an enemy. exit early }
doesnt work because it doesnt know what hitCollider is. If this isnt a raycast how do i define the hit?