Search Unity

[SOLVED] Position Crosshair with Raycast

Discussion in 'Scripting' started by Hero101, Nov 22, 2017.

  1. Hero101

    Hero101

    Joined:
    Jul 14, 2015
    Posts:
    158
    I can't figure out why this code isn't working. In my 3D spaceship game I have a raycast coming out of the ship's muzzle (empty game object) and I am trying to position a crosshair (UI image) where the raycast hits.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CrosshairTest : MonoBehaviour {
    6.  
    7.  
    8.     public Transform crosshair;
    9.     public Camera cam;
    10.     public Transform muzzle;
    11.  
    12.     void Update ()
    13.     {
    14.         RaycastHit hit;
    15.         if (Physics.Raycast(muzzle.transform.position, muzzle.transform.forward, out hit))
    16.         {
    17.             if (hit.collider)
    18.             {
    19.                 crosshair.transform.position = cam.WorldToViewportPoint(hit.point);
    20.             }
    21.         }
    22.     }  
    23. }
    In the game window the crosshair just stays in the bottom left corner. What am I doing wrong?
     
  2. TheHighGround

    TheHighGround

    Joined:
    Nov 19, 2017
    Posts:
    68
    switch to cam.WorldToScreenPoint(hit.point);

    I'm assuming 'crosshair' is a UI Image Component? If so change it to RectTransform. If you do that do

    crosshair.position = cam.WorldToScreenPoint(hit.point);
     
    oranchad, Hero101 and MaxGuernseyIII like this.
  3. MaxGuernseyIII

    MaxGuernseyIII

    Joined:
    Aug 23, 2015
    Posts:
    315
  4. Hero101

    Hero101

    Joined:
    Jul 14, 2015
    Posts:
    158
    That did the trick! Thank you! Just so I better understand for future work, why did it need to be WorldToScreenPoint instead of WorldToViewportPoint?
     
  5. TheHighGround

    TheHighGround

    Joined:
    Nov 19, 2017
    Posts:
    68
    Camera.WorldToViewPort API TLDR: a viewport is a normalized Vector2 you get a value from 0.0F to 1.0F. On the XAxis the left most part of the screen would be 0.0F and the right most port of the screen would be 1.0F.

    Camera.WorldToScreenPoint API TLDR: a screen point is the raw Vector2 that represents the screen in pixels. So if you have a screen that is 1920x1080 the coordinate (x,y) a UI RectTransform.position component would be placed would be relative to that screen size.
     
    MLipscomb and Hero101 like this.
  6. Sonfernando

    Sonfernando

    Joined:
    Mar 12, 2018
    Posts:
    1
    Graciasssss