Inaccurate Raycasting

NOTE:: This only occurs AFTER moving the camera… So I’m guessing it has something to do with SmoothFollow

I’ve uploaded a web-player version so you can see what’s going on, please note everything in here is basic and the GUI will be mal-scaled because I haven’t worked on scaling anything yet. Either way, here it is in a nutshell…

The raycasting seems to come from the camera, although everytime I use it, it starts at a location lower then the last, which in term is making the raycast very inaccurate. The camera has a smooth-follow script attached to the player, if this could be causing the problem?

  • Hit Y and Z to spawn a new NPC (They have different names, only visible in Console currently)
  • Will spawn a capsule, just look for it, each NPC will be +10z away from eachother
  • Click to target, healthbar will appear to right if targetting

Note: You CAN target it, you just have to click all around it numerous friken times…

Raycasting code used

 if (Input.GetMouseButtonUp(0))
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast (ray, out hit, 250))
				if(hit.transform.tag == "Untagged") return;
                if (hit.transform.tag != "terrain")
                    target = hit.transform;
					Debug.Log ("Hit something: " +hit.transform.tag);
                } else {
					target = null;

EDIT: While debugging further I’ve noticed that even while clicking on the NPC, 70% of the time the Raycast hits the terrain, not the NPC… I’m not sure what would be causing this, is it going through the NPC?

Edit2: using Debug.DrawLine I noticed that there were two ray-cast lines being drawn, one hitting where it should, and another coming from somewhere unknown (Not the camera, although below it) hitting slightly before it should, scaled down at a lower angle… So, I believe I found my brother, now I just need to find a fix.

EDIT3: It seems that if I HOLD the raycast button down for around 20seconds the secondary Raycast will gradually fall below the terrain and not interact with anything anymore, although this still worries me as to why there is a secondary Raycast.

It feels like you’re doing this in FixedUpdate. Could that be? I’m too lazy to download and decompile :smiley:

Never do such things in FixedUpdate. FixedUpdate is for physics calculations. You can’t process any event information there because events are evaluated once per frame. If your visual framerate is greater than the fixedUpdate rate it’s pure luck when a MouseDown event happens in exact the same frame where a FixedUpdate is called.

I’ve made a visualisation of how FixedUpdate works some time ago. Just play with the “framerate” setting and see when Update is called and when FixedUpdate is called.