Since our Game has Light Bullets that can be shot from our Lantern, we needed a way to visualise the Aiming direction.
We’ve chosen to do this using a Crosshair on the middle of the screen as overlay. The current crosshair is just a temporary placeholder and can be easily changed into something more obvious or subtle, so that it fits our theme.
Calculating at which object you are looking was, however, a bit more difficult. We need to cast a ray starting from our player towards the direction of the camera, however, this would result in either having the crosshair on the back of our Player, or aiming below our crosshair if we move our Camera upwards.
To fix this, we cast a ray at the the position of our player but with this height offset kept in mind. This will give us the correct direction to cast the ray, which will then return the Collider you were looking at. This hit point can be used to then calculate the direction from the lantern, so our bullet can be fired towards the targeted object.
These directions can be visualised to debug. In the video below, the Red line represents the direction from the ray, while the Green line represents the direction for the bullet. The point where these lines intersect, should be the position of where your crosshair was looking at.
A final issue that came up, was when the Ray didn’t collide with anything (i.e. Looking at the Sky). We needed a default point somewhere in the distance to set as Target. Using the Far Plane of our Camera (The point where anything further won’t be seen, thus creating “sky” from this distance on) seemed like a good idea at first, but since the Far Plane didn’t match with the Distance that our bullets reached, I stepped away from using this.
Instead, I’m calculating the distance that a bullet can reach (lifeTime * speed) and set this as “far plane” (Note that this isn’t actually the Far Plane of the camera, but instead an imaginary plane with which the Ray will collide in case it hasn’t collided before).
This results in our bullet always reaching the crosshair position right before it vanishes due to its lifetime. This can also be seen in the video at the top, and in the debug view (second video) the lines will indeed intersect at the point where the bullet vanishes.