Search Unity

Question How to raycast forward of a Ui image on a canvas in screen space overlay

Discussion in 'UGUI & TextMesh Pro' started by Bigfella69, Jul 9, 2020.

  1. Bigfella69


    Jul 6, 2020
    Hey team,

    I'm making a 3rd person game that relies heavily on movement by grappling hooks. I have a canvas in screen space overlay that has a couple of images on it that act as the pieces of the cross hair. The crosshair is centered by default but on holding the shift key the left and right cross hairs move outward from center along the x axis and then return back to center on release. I have two grappling hooks that need to fire from the player to whatever is directly behind these crosshairs at the time the hooks are fired.

    I already have this all up and running and the grappling hooks fire to the points that I need them too. However my problem is that this only works because I figured where on the screen these points were at what time and managed to raycast with ViewPointToRay from the screen. The code I use is bellow where the variable "anchorL" is the position on the x axis that the left crosshair happens to be at that time.

    Ray ray = cam.ViewportPointToRay(new Vector3(anchorL, 0.5f, 0));

    My problem is that this system all falls to pieces when the screen window size etc is altered. I.e it works perfect in unity when the player is in full-screen mode, but doesn't line up when it is in windowed mode. I would like to create a better more accurate system where I raycast forward of the actual crosshair images on the screen space overlay, instead of doing what I am now and guessing their position on the screen. Either that or some way of controlling the crosshairs on the screen with ratios instead, as I'm using ratios for the screen x position that I'm ray casting from. I also have a problem where sometimes as im swinging around the place some of the raycasts somehow go backwards and hook onto surfaces that are behind the player. Any thoughts would be appreciated on either of these two issues.

    Thanks in advance.