- Home /
raycast help need
I want to create a small ray which can tell my villager if there is tree in front of him.
This is what i done but it don't work how i want
function Update () {
var hit : RaycastHit;
if (Physics.Raycast (transform.position, -Vector3.one, hit, 100.0)) {
distanceToGround = hit.distance;
print ("There is something in front of the object!" + distanceToGround);
}
}
Can you help me?
Cheers!
Answer by skovacs1 · Aug 25, 2010 at 02:28 PM
What your code does:
//Every frame
function Update () {
//Casts a ray 100 units in the direction x=-1, y=-1, z=-1 from the current position.
//You are always casting in the same direction in world space, not relative to your
//character.
var hit : RaycastHit;
if (Physics.Raycast (transform.position, -Vector3.one, hit, 100.0)) {
//Unless your ground is always diagonally down in world space, this variable is
//misnamed, especially since the diagonal distance is less consistent and
//probably not what you wanted anyways.
distanceToGround = hit.distance;
//Since you aren't casting in front, this message is wrong.
print ("There is something in front of the object!" + distanceToGround);
}
}
What you probably want:
//Every frame
function Update () {
//Cast a ray 100 units in the forward direction from the current position
var hit : RaycastHit;
if (Physics.Raycast (transform.position, transform.forward, hit, 100.0))
print ("There is something in front of the object!" + hit.distance);
}
You should really try to understand what your code is doing - it becomes very obvious what's wrong when you know exactly what's happening step by step.
In order for the raycast to work, the object you want to collide with will need to have a collider attached. Also, I recommend using layers and a layermask to reduce the cost of the raycast.
Your answer
Follow this Question
Related Questions
Help with Raycast on Render Texture 0 Answers
Raycasting and HTC Vive. 0 Answers
Updating line positions with reflections 1 Answer
How do I make it know what it's hitting? 3 Answers