Distance on fps

Im trying to create a readout onto a gui so that when the crosshair is pointed at a object then it feeds out distance to that object. Its for sniping fps. I already know how to do the gui so if anyone can help with the distance calc from camera to object thatd be great. The main problem im havin is working out on the fly which object is being looked at. Thanks for any help anyone can give me. oh btw prefereably in java.

If your objects have colliders, see this question for some help. Otherwise it's more complex...

Is there a maximum distance at which targets should no longer be recognized? There are a couple of ways you could do this. The best I think would be to raycast a few times per second (not every frame, waiting .3 second isn't that bad for this kind of 'readout') from the camera to infinity (or your max range) in that direction. Pull up the docs and look up `Camera.ScreenPointToRay`, that will get you started. This function takes a point in screen space (Z is ignored) and gives you a `Ray`, that starts at that spot on the camera's near clipping plane and goes in the camera's forward direction. You would then use `Physics.Raycast` to do the distance check. Look for the version(s) of `Physics.Raycast` that also take a `RaycastHit` as input. From that you check which collider or tag you hit, and if it's something appropriate, the actual collision point is stored inside the Raycasthit variable, and the distance check is a simple `(VectorB-VectorA).magnitude` check.

You can use the layer collision matrix if you want to be able to 'target' the baddies through things like bushes and the like. Everything that should not be considered an obstacle or a baddie should go on the IgnoreRaycast layer.

Once you've got this working you can also take things a step further if you want, and outline or highlight targets in various colors based on whether they're friendly, hostile, or any other criteria for targets and environment pieces you're targeting - or alert them that they're being targeted, etc. You've already got a reference to the GameObject in question.

You need to have a collider on your objects.

If thats the case you can use a ray from the camera to see if its intersects.

var ray = Camera.main.ScreenPointToRay (Input.mousePosition); var hit : RaycastHit; if (Physics.Raycast (ray, hit, 100)) { Debug.Log( "Hit something at:"+hit.distance); }