Question About Ray casting in an Area and Perspective

Hi,

I am making the code for tracking on my missile launcher (not the missile but the target). The target is not acquired instantly instead the player must hover the scope over the target for a couple of seconds until it is acquired then fire. However if the target moves out of the area of the cross hair then the timer is reset.

I haven’t started coding yet but realise the two biggest problems are working out when the target leaves the area of the scope (considering that the area occupied by the scope is much greater at the targets location due to perspective) using raycasting in an area which I have not done before.

Second problem that I reckon I can solve is making a 2D texture appear over the target which will use Camera.WorldToScreenPoint() to convert the location of the target into a screen location.

I need help with the first problem. How can I ray cast in an area and work out the size of that area at the target?

Thanks

How difficult the problem is depends on how precise you want to be and how you define ‘within the cross hair’. For something simple like making sure the center position of the target stays within a circular area, Simply use WorldToScreenPoint() and compare the distance of the screen center position of cross hair with position of the target. If it is below some radius, then it is within the crosshair. By converting to screen coordinates, you’ve already projected the 3D world position onto a 2D plane. If you want to make sure that the entire target stays within the cross hair, then you will have to compare the cross hair screen position with the eight bounding box positions of Renderer.bounds. Since bounds will likely include a bit more than the actual target, this is not perfect.

You should probably find the angle between the line from the launcher to the target and the direction forward of your launcher. Something like

Vector3 direction=target.position-launcher.position; 
float angle=Vector3.Angle(launcher.forward,direction);

then you check if the angle is in the range you want. Far easier than raycasting to a plane with a variable size.