Drawing a Line for a Smart Crosshair

Okay guys, I’ve run into a bit of a snag. Hopefully someone here can shed some light on the subject. Here goes!

I want to draw a line or a ray(whichever would be ideal) from my player to a set distance directly in front of him on the Z axis.

Let’s say, for example, I wanted to draw a ray/line that stopped 10 yards away and have the end of that line draw a crosshair. The line would also need to stop and draw the crosshair on whatever it collided with, if anything. I think this would be a very useful subject to discuss. I’ve been reading up and I couldn’t really find too much on the subject.

I can’t really think of an example from another game, but I’m sure someone’s done it.

Any and all help would be greatly appreciated!

Hello there!

The first thing you’ll be needing is the start position and the direction. A ray contains both these variables. Since you’re using a cross hair I’m going to go ahead and presume that you’re doing this in a first person perspective.

Ray ray = Camera.main.ScreenPointToRay(Screen.width / 2, Screen.height / 2);
RaycastHit hit = new RaycastHit();
Vector3 crosshairPosition;

if(Physics.Raycast(ray, out hit, maxDistance))
    crosshairPosition = ray.origin + ray.direction * hit.distance;
else
    crosshairPosition = ray.origin + ray.direction * maxDistance;

There you have it! That should be the position you wanted.

Thanks for the reply. I’ve been messing with it and it works pretty well so far. I have to fine-tune it a little bit. This crosshair will be a sweet thing to have. I look forward to sharing screenshots and a demo with you all soon!