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

Visual indicator for aiming

Discussion in 'Scripting' started by orgia, Jul 17, 2017.

  1. orgia

    orgia

    Joined:
    Jun 24, 2017
    Posts:
    14
    Chapter 3 in "Unity in Action" .In order to set a visual indicator(*) for aiming in the central of screen, line 17 & 18 as below, I knew that it subtracted size/2 from _camera.pixelHeight/2 will get the central point of Y axis, but why didn't subtract size/2 but size/4 from _camera.pixelWidth/2?



    Code (CSharp):
    1. public class RayShooter : MonoBehaviour {
    2.  
    3.     private Camera _camera;
    4.  
    5.  
    6.     // Use this for initialization
    7.     void Start () {
    8.         _camera = GetComponent<Camera> ();
    9.  
    10.         Cursor.lockState = CursorLockMode.Locked;
    11.         Cursor.visible = false;
    12.     }
    13.  
    14. //*character * displayed in the center of the screen
    15. void OnGUI(){
    16.       int size = 12;
    17.        float posX = _camera.pixelWidth / 2-size/4;
    18.         float posY = _camera.pixelHeight / 2-size/2;
    19.         GUI.Label (new Rect (posX, posY, size, size), "*");
    20.     }
    21.  
    22.  
    23.     // Update is called once per frame
    24.     void Update () {
    25.         if (Input.GetMouseButtonDown(0)) {
    26.             Vector3 point = new Vector3 (_camera.pixelWidth /2, _camera.pixelHeight /2,0);
    27.             Ray ray = _camera.ScreenPointToRay(point);
    28.             RaycastHit hit;
    29.  
    30.             if (Physics.Raycast(ray,out hit)) {
    31.                 StartCoroutine(SphereIndicator(hit.point));
    32.             }
    33.         }
    34.     }
    35.     private IEnumerator SphereIndicator(Vector3 pos)
    36.     {
    37.         GameObject sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
    38.         sphere.transform.position = pos;
    39.         yield return new WaitForSeconds (1);
    40.         Destroy (sphere);
    41.     }
    42. }
    43.  
     
    Last edited: Jul 17, 2017
  2. Phorsaken

    Phorsaken

    Joined:
    Dec 12, 2013
    Posts:
    27
    This looks like an older way of doing things. With the new UI you really only need to center anchor your target radical and use that.

    -Alexander
     
  3. orgia

    orgia

    Joined:
    Jun 24, 2017
    Posts:
    14
    thanks for replying , I will figure out how the new UI works