- Home /
Raycast Distance Help
function Update () {
var fwd = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
}
Here I have a raycast on object that will try to detect objects in front of it. If there is an object then take the distance (hit.distance) and change it into a int variable. (In Javascript)
So basically:
var dis : int = hit.distance
However for some reason it represents dis as 0.
Yes, you need to take it to a float. $$anonymous$$y guess is that the raycast is colliding with the same object that's firing it and then when you cast it to an integer, it chops off any small value that that original raycast might have returned. So do this:
1) Add a layer mask to your raycast to ignore the object that's shooting it
2) Store the distance in a float, not an integer
even if I take it as a float like :
var dis : float = hit.distance;
the variable dis still equals to 0 when hit.distance equals to 8.2
Answer by redeemer · May 18, 2015 at 11:09 AM
Acording to your code, you're not actually raycasting anything, but only declaring the variables to do so.
Try this :
function Update () {
var rayLength = 10;
var hit : RaycastHit;
var fwd = transform.TransformDirection (Vector3.forward);
if (Physics.Raycast (transform.position, fwd, hit, rayLength)) {
print ("Hit Distance : " + hit.distance);
}
}
You should read this too http://docs.unity3d.com/ScriptReference/Physics.Raycast.html.
I have this: function Update () { var fwd = transform.TransformDirection(Vector3.forward); var hit : RaycastHit; var dis : float = hit.distance;
if (Physics.Raycast(transform.position, fwd, hit)){//IF I HIT SO$$anonymous$$ETHING
print (dis); //Equals to 0 all the time
print (hit.distance); //If equals to 8
}
}
You are trying to assign the hit.distance before it's populated, what surprises me is the fact that you get 0 ins$$anonymous$$d of null. Anyway, your code should be something like the above I already posted.
You also need to multiply your forward vector times the distance you want to cast. The forward, up or right vector are unitary, they only indicate the "direction" and always have a value of one. SO if you don't multiply it, you will be casting only 1 meter from you original pos.
Try the following, it should work :
function Update () {
var fwd = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
var rayLength = 10;
if (Physics.Raycast(transform.position, fwd * rayLength, hit)){//IF I HIT SO$$anonymous$$ETHING
var dis : float = hit.distance;
print (dis); //Equals to 0 all the time
print (hit.distance); //If equals to 8
}
}
I know it's kinda obvious, but just in case, be sure the object you want to detect have a collider and it's not set to trigger.