Raycast Ignoring Distance

Hi There.

I have setup a raycast to fire when I hit the mouse button, but it is completely ignoring the distance parameter and I don’t know how to fix it, any help would be great!

Here is my code:

var fwd = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
if(Physics.Raycast(transform.position, fwd, hit, 1))
	print("I Hit " + hit.transform.name);

Cheers, Bradley.

What kind of testing set-up do you have? I find, that when something seems broken enough I have to stop and ask, it’s worth making a real test scene.

Paste just your code into an empty, in a new scene. Make just one cube to fire at. Change the code a little to make testing easier – raycast every frame and always print something. I use C#, so this is probably a bit wrong:

var result : string;

function Update() {
  if(Physics.Raycast( transform.position, transform.forward, hit, 1)) {
    result = "hit " + hit.transform.name + " at + " hit.distance";
  else {
    result = "missed";

Move the empty around in scene view, to test. result will always right-away tell you about the raycast (as long as the empty is selected.) I think distance will work fine. But then you can add more parts of your real scene, and find the broken part (do you have any large triggers?)

NOTES: transform.forward is the short version of transformDir(V.forward). Both versions just give your local blue arrow, and transform.forward is shorter. Double-check the parms. There are so many versions of raycast that it’s easy to switch distance and layermask, but what you have looks good (and it exactly matches an example in the docs. But, in general, easy to flip inputs.)

I wouldn’t bother drawing a ray. The syntax is a little different than for a raycast, so it’s easy to have the ray be wrong, or have it confuse you about the raycast. Plus, the ray is your local blue arrow. DrawRay is great for more complex stuff. Like your enemies are avoiding imaginary obstacles and you need to know what all the “feeler” raycasts think is blocking them.