help with spherecast()...

I am a little lost about spherecast() ! Can someone translate the code below from raycast to spherecast();

var zoa = 0 ;
var hit = new RaycastHit();

function Update () {

   if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) {

     var ray = Camera.main.ScreenPointToRay (Input.GetTouch(0).position);
     if (Physics.Raycast (ray, hit)) {
       if (hit.transform.gameObject == GameObject.Find("Duck") ) 
         zoa=zoa+1; 
    } 
}

Hi,

Please check your formatting. It looks like some of your code is formatted as code, and some is not. You’ll get better responses with well-formated code, because it’s easier to read.

While raycast and spherecast work similarly (you cast out a physics “shape” and get true or false back if a hit occurred, and additionally details on the hit if you passed a hitinfo), there is no direct translation from raycast to spherecast. This is because you define a ray and sphere differently.

A ray is a 3d direction and a starting point. A Sphere is all that, plus a radius to define the sphere.

So, your code would additionally need to define the radius for the sphere cast. Otherwise, the same code would work (if it worked for your purposes in the first place).

Just follow the parameters described here http://docs.unity3d.com/Documentation/ScriptReference/Physics.SphereCast.html

You can pick with of the 3 options you want. If you don’t specify a distance, it’ll try to match you sphere projection out forever; if you don’t specify a layermask, it’ll report the first thing it bumps, regardless of layer.

Try this code:

var zoa = 0 ;
var hit = new RaycastHit();
 
function Update () {
 
   if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) {

     var radius = 1;   
     var ray = Camera.main.ScreenPointToRay (Input.GetTouch(0).position);
     if (Physics.SphereCast (ray.origin, radius, ray.direction, hit)) {
       if (hit.transform.gameObject == GameObject.Find("Duck") ) 
         zoa=zoa+1; 
    } 
}

radius is the radius of the sphere (basically, spherecast casts a thicker ray, so the radius is the thickness of the ray).