[SOLVED] Ray from Player to Crosshair in 2D Game

Dear CommUnity,

This question seems fairly basic, but I couldn’t find helpful answers through google/forum search.
I’ve got a 2D Sidescroller and a Crosshair for aiming. What’s the simplest way to launch a ray from the player in direction of the crosshair?

Thx in advance,
Moritz

Use trigonometry to find out the angle to the coordinate. … or maybe there is a helpful unity function?

thx for your answer, imaginaryhuman.
I assume there’s a function for that, but even if i use trigonometry and hence got a slope, what function do I have to use for firing the ray using the slope?

Thank you!
moritz

The easiest would be using a linecast (which works like the raycast, but you feed position vectors instead of the start and the direction).

Physics.Linecast(player.position, crosshair.position);

If for any reason you would need to get a direction, you can easily calculate it by substracting the crosshair position with the player position, and normalizing the result.

Vector3 dirToCrosshair = (crosshair.position - player.position).normalized;

You can find out the angle on the Z coordinate by using Mathf.Atan2

float angle = Mathf.Atan2(dirToCrosshair.y, dirToCrosshair.x)

Dear Damizean,

Unfortunately the Physics.Linecast method isn’t a ray but a line, hence it’s got a start and endpoint (a ray is normally infinite). Therefore, a ray is better for collision detection.
However, your “(crosshair.position - player.position).normalized;” inspired me to solve the problem.
First of all I had to transform crosshair.position (2D screen coords) in a Vector3. Then I had to get the screen coords of player.position using Camera.WorldToScreenPoint.
With some additional stuff for centering the screen coords point (0,0) I could finally get a direction-vector I can successfully use with Physics.Raycast
So thanks a million for this idea Damizean!

Thank you and regards,
Moritz