Detect collision with raycast

I need to be able to detect if an enemy is collided with the SphereCast and if so add that enemy to an an Array. My problem is that the counsel gives me an error saying "collided is not a memeber of unit RaycastHit.

var enemysInRange = new Array();

var hits : RaycastHit;

function Update () {
if(Physics.SphereCast(transform.position, 50, transform.forward, hits, 0.1)){
Debug.Log(hits.collider.tag);
}
}


function OnCollisionStay(collided : Collision){
if(hits.collided.tag == "Enemy"){
enemysInRange.Push(hits.gameObject);
Debug.Log("Unit Pushed");
}

}

I'm sorry but I don't see any raycasting here

if(Physics.Spherecast) is a rayucast but in the shape of a sphere

yeah that get's me confused so where is the ray line? start ray line, ... and what's wrong with this? hits.collided.tag if I see correctly you are makeing 2 vars hits collided you just can't make hits.colided or colided.hits try doing colided.colider.gameObject.tag or something among that don't know play with words after every . you make it'll help you get the answer truthfully to say I've never saw (collided : Collision)

if(Physics.SphereCast(transform.position, 50, transform.forward, hits, 0.1)){ This line is creating the SphereCast

1 Answer

1

short version

if(hits.Collider.tag == "Enemy")

long version:

hits should be renamed to hit if you’re only doing a single spherecast.
If you want to return an array of each collider hit you should do a SphereCastAll, which will return an array of “hits”

you should do your spherecast in FixedUpdate instead of Update() or else you’ll run into precision issues.

Physics.Spherecast won’t return a hit on a collider set up as a trigger.
It also returns all of the info you need to manipulate the target hit.

To use the OnCollisionStay method you should put that on your target and place a collision sphere on your tank, which will save you the sphere cast entirely.