Search Unity

keeping crosshair on screen

Discussion in 'Scripting' started by bananapizzuh, Jan 16, 2022.

  1. bananapizzuh

    bananapizzuh

    Joined:
    Jan 2, 2021
    Posts:
    7
    My crosshair is made with a couple of different vectors that is placed in a screen space camera canvas. I have tried to clamp it with different values to clamp to, none have worked. Anyone know how I can clamp it? And also does clamping something effect rigidbody velocity?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    I like to handle this by anchoring a GameObject in the UI at LowerLeft, and then one at UpperRight.

    Then my script just has public Transform references to each of those and I use their positions.

    Code (csharp):
    1. float croppedX = Mathf.Clamp( mouseX, LowerLeft.position.x, UpperRight.position.x);
    2.  
    3. // ditto above for Y...
    4.  
    5. // and now use croppedX/croppedY to position your crosshair.
    6.  
    Super-simple, plus the cropping instantly changes if the screen changes shape. You can also inset them slightly so that the entire + of the crosshair is onscreen, if you prefer.
     
    bananapizzuh likes this.
  3. bananapizzuh

    bananapizzuh

    Joined:
    Jan 2, 2021
    Posts:
    7
    Would I turn the new x and y into a Vector2 and put that as the transform?
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    Yes! I left that part out to sorta make it clear how I was clamping X. Will edit.