Search Unity

Drawing a Line for a Smart Crosshair

Discussion in 'Scripting' started by xenbiosis, Mar 4, 2011.

  1. xenbiosis

    xenbiosis

    Joined:
    Jan 28, 2011
    Posts:
    49
    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!
     
  2. Myx

    Myx

    Joined:
    Nov 29, 2010
    Posts:
    196
    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.

    Code (csharp):
    1.  
    2. Ray ray = Camera.main.ScreenPointToRay(Screen.width / 2, Screen.height / 2);
    3. RaycastHit hit = new RaycastHit();
    4. Vector3 crosshairPosition;
    5.  
    6. if(Physics.Raycast(ray, out hit, maxDistance))
    7.     crosshairPosition = ray.origin + ray.direction * hit.distance;
    8. else
    9.     crosshairPosition = ray.origin + ray.direction * maxDistance;
    10.  
    There you have it! That should be the position you wanted.
     
  3. xenbiosis

    xenbiosis

    Joined:
    Jan 28, 2011
    Posts:
    49
    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!