- Home /
Ray cast downward for ground collision
I would like to cast a ray downward to see if the ray collides with the ground. Here is what I have so far.
function Update{
var downDirection : Vector3 = Vector3(0,-10,0);
Debug.DrawRay (transform.position, Vector3.downDirection, Color.green);
}
How would I go about actually detecting a collision and returning a boolean as true if such collision were detected while still drawing the ray.
Answer by shigidaMark · Jan 03, 2013 at 06:27 PM
var hit : RaycastHit;
var dist : float;
var dir : Vector3;
function Update(){
dist = 10;
dir = Vector3(0,-1,0);
//edit: to draw ray also//
Debug.DrawRay(transform.position,dir*dist,Color.green);
//end edit//
if(Physics.Raycast(transform.position,dir,hit,dist)){
//the ray collided with something, you can interact
// with the hit object now by using hit.collider.gameObject
}
else{
//nothing was below your gameObject within 10m.
}
}
Seems to work fine, but could you explain what the "hit: is in (transform.position,downDirection,hit,dist)
and where I would include a debug.drawray so it draws the exact same ray that is being casted
just added the DrawRay() function...
The hit is a RaycastHit object. It contains information about the object being hit and the point at which it was hit.
http://docs.unity3d.com/Documentation/ScriptReference/RaycastHit.html
you could actually just not use it at all (just remove it), the Raycast method is overloaded and calling the method with just the other arguments mentioned is enough to check if 'something' is hit. But to interpret if your character is hitting terrain or something you could do a check against the hit object's tag or name:
if(Physics.Raycast(transform.position,dir,hit,dist)){ if(hit.collider.tag == 'Ground'){ //character is within 10m of the ground } }
Can you translate this code to C#? I realle need it please.
Answer by Janibasha · Jun 28, 2018 at 12:19 PM
not working, always working
else{ //nothing was below your gameObject within 10m. } else part only
Answer by QuarterMillion · Aug 08, 2021 at 05:44 AM
//for C# version of suggested code
//I'm pretty sure that this var hit : RaycastHit;
//could be written as this RaycastHit hit;
//so following that logic
RaycastHit hit;
float dist;
Vector3 dir;
//Otherwise everything else should probably remain //the same
Your answer
Follow this Question
Related Questions
GameObjects being instantiated on top of each other 1 Answer
Zombie attack script animation help! 0 Answers
Smoothing Directionally between three materials 1 Answer
cannot create key in keystore 1 Answer
Help with Java socket server 1 Answer