raycast hit distance issue
The Distance variable just turn into random numbers when i click the mouse button. What did i do wrong? Please help :)
var TheDamage : int = 50; var Distance : float; var MaxDistance : float = 1.5;
function Update() {
if (Input.GetMouseButtonDown(0)) {
var hit : RaycastHit;
Distance = hit.distance;
Debug.Log("Pressed left click.");
if (Physics.Raycast (transform.position, transform.TransformDirection(Vector3.forward), hit)) {
Distance = hit.distance;
if (Distance < MaxDistance)
{
hit.transform.SendMessage("ApplyDamage", TheDamage, SendMessageOptions.DontRequireReceiver);
}
}
}
}
Dont you want transform.forward ins$$anonymous$$d of Vector3.forward? Local forward vector to world space, right?
It still does not work. I think the main issues is :
The hit.distance updates at random times when i click the mouse button, like every 10th time. Why? And what can i do to fix it?
When the hit.distance updates it is a completly wrong number, i dont know why, but there must be something wrong in the script. Please help! :)
Here is the script:
#pragma strict
var TheDamage : int = 50;
var Distance : float;
function Update ()
{
if(Input.Get$$anonymous$$ouseButtonDown(0))
{
var hit : RaycastHit;
if (Physics.Raycast (transform.position, transform.TransformDirection(transform.forward), hit))
{
Distance = hit.distance;
}
}
}
Answer by rutter · Dec 01, 2015 at 12:26 AM
This line appears twice:
Distance = hit.distance;
A RaycastHit
is only safe to access after it has been used in a raycast call, and even then only if that call returned true
(indicating that a hit occurred).
The first Distance = hit.distance;
occurs before you've actually fired a raycast, which means that you may be reading garbage data.
You should only read from hit
if the raycast returns true.
Your answer
