- Home /
Check if target is in range from Raycast
I am trying to write a script where a NPC shoots a raycast at an enemy and it checks to make sure that the target is in range. When I run the script with no range things it works fine and even comes back with a distance. When I plug that distance in or any other distance (even up to 1000x the original distance) I get nothing back. Code is bellow what am I doing wrong?`I am trying to write a script where a NPC shoots a raycast at an enemy and it checks to make sure that the target is in range. When I run the script with no range things it works fine and even comes back with a distance. When I plug that distance in or any other distance (even up to 1000x the original distance) I get nothing back. Code is bellow what am I doing wrong?`I am trying to write a script where a NPC shoots a raycast at an enemy and it checks to make sure that the target is in range. When I run the script with no range things it works fine and even comes back with a distance. When I plug that distance in or any other distance (even up to 1000x the original distance) I get nothing back. Code is bellow what am I doing wrong?
function shoot (){
var layerMask = 1 << 8;
var Rangeofgun : float = 118;
var impactpoint: float;
var fwd = transform.TransformDirection (Vector3.forward);
var ray = new Ray(transform.position, transform.forward);
var hit : RaycastHit;
if (Physics.Raycast(ray, hit)){
impactpoint = Rangeofgun - hit.distance;
if (impactpoint == 0){
Debug.Log("It Worked");
}
}
}
`
Answer by AlwaysSunny · Jul 31, 2015 at 03:52 PM
You're asking whether the hit point is exactly as far away as the range of the gun. That doesn't appear to make any sense. Check that it's less instead.
if (Physics.Raycast(ray, hit)){
if (hit.distance <= Rangeofgun){
Debug.Log("It Worked");
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220611233839im_/https://answers.unity.com/themes/thub/images/avi.jpg)