Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Raycast to screen edge and get Vector3?

Discussion in 'Scripting' started by jtsmith1287, Oct 25, 2014.

  1. jtsmith1287

    jtsmith1287

    Joined:
    Aug 3, 2014
    Posts:
    787
    I'm trying to get a target via raycasting from a varying position on the screen, but don't want to target things off screen. I was thinking of getting the magnitude of a vector from the position on screen to the screen edge and setting that to the max distance of the ray to that. I don't however know how to do this. I know how to get the edge of the screen, but not a specific points along that edge. Halp!

    PS the camera is stationary and it's a top-down game.
     
  2. RiokuTheSlayer

    RiokuTheSlayer

    Joined:
    Aug 22, 2013
    Posts:
    356
    I'm not completely sure if this is what you're saying, but if it is, you COULD see if the object you're targeting is off-screen, and if not, ignore it, rather than making the raycast not hit beyond the screen.

    Of course, if you wanted to do that, you could make a collider around the edge of the screen, and only let the raycast hit it. Both would work really.

    If this isn't what you meant, sorry, haha.
     
  3. Diablo404

    Diablo404

    Joined:
    Mar 15, 2013
    Posts:
    136
    In addition to what @RiokuTheSlayer said, you can test the renderer like so :
    if( renderer.isVisible == true )
    But BEWARE, in Edit mode, if your Scene window can "see" the objects, it will be triggered as isVisible = true;

    And as RiokuTheSlayer said, if it's not what you were needing, sorry, or maybe explain things a bit more with some code so we can try to help!
     
  4. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
  5. jtsmith1287

    jtsmith1287

    Joined:
    Aug 3, 2014
    Posts:
    787
    All of your suggestions are great, and I may just do the WorldToScreenPoint. I'm already using it for other things, but it just seemed cheaper to only cast to the screen edge. But I guess since I'd have to calculate that magnitude every frame anyway... hmm... *thinking outloud*. Ok ya, the WorldToScreenPoint will work best. Thanks guys!
     
  6. RiokuTheSlayer

    RiokuTheSlayer

    Joined:
    Aug 22, 2013
    Posts:
    356
    Yep!
     
  7. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190