Help with ray cast

Hi guys i was wondering if someone could help me. well basically i am making an ray shoot out of the cam but it does not work. i said if the ray hits the gameobject with the tag “Floor” print you hit floor. But it is not working :frowning:

here is my script:

function Update () {
var hit : RaycastHit;
var camray : Ray = Camera.main.ScreenPointToRay(Vector3( Screen.width / 2 , Screen.height / 2, 0));
//Debug.DrawRay(transform.position, Vector3.forward * 50, Color.red);

if(Physics.Raycast(camray, hit, 50)){


   if(hit.collider.gameObject.tag == "Floor"){
   
   Debug.Log("you hit the floor ");  

}
}
}

also how do i get the ray to be viewable in the scene mode normally i did :

Debug.DrawRay (transform.position, Vector3.forward * 10 , Color.red);

this does not work when i try and do it for the camera how do i do that ?

i would be really thank full if someone could help me :slight_smile:

Well, is it possible that your floor is more than 50 units away, or in front of the near plane of the camera? The ray created by ScreenPointToRay starts at the near plane. And you limited the Raycast to 50 units. The other possibility is that the floor has no collider.

To draw the ray, you need to use

Debug.DrawRay(ray.origin, ray.direction * 50, Color,red);

You had used transform.position and Vector3.forward which have nothing to do with the ray.

Can you try below:

var ray = new Ray (Camera.main.transform.position, Camera.main.transform.forward);
Debug.DrawRay (Camera.main.transform.position, Camera.main.transform.forward* 10, Color.green);

var hit : RaycastHit;
if (Physics.Raycast (ray)) {
  if(hit.collider.gameObject.tag == "Floor"){

   Debug.Log("you hit the floor ");  
   }
}

There are 2 reasons for the ray to be not visible:

1- Debug.DrawRay only draws in the Scene view; you can enable it in the Game view too by clicking the Gizmos button (on the top of the Game view);

2- Since the ray goes from the center of the camera to the center of the screen, the only thing you will see (if any) is a red dot; try to offset the origem 0.5 downwards

function Update (){

  var hit : RaycastHit;
  var camray : Ray = Camera.main.ViewportPointToRay (Vector3(0.5,0.5,0));
//  Debug.DrawRay(transform.position, Vector3.forward * 50, Color.red);
  if(Physics.Raycast(camray, hit, 50)){
    Debug.Log("you hit "+hit.collider.gameObject.name);  
  }
}

//20 is a distance
var ray = new Ray (Camera.main.transform.position, Camera.main.transform.forward20);
var hit : RaycastHit;
Debug.DrawRay (Camera.main.transform.position, Camera.main.transform.forward
20, Color.green);
if (Physics.Raycast (ray, hit, 20)) {
Debug.Log(hit.collider);
}
else{Debug.Log(“EMPTYNESS”);}

If this aint gonna help you, than speak to the Dark Vaider of Matrix :D