Fire Raycast Toward Current Mouse Position

Currently I have a fixed camera and a reticule which follows the position of the mouse onscreen. The reticule script is attached to an otherwise empty game object and uses GUI.DrawTexture. The raycast script is attached to the camera object.

I want to eventually throw a ball projectile from the camera’s position towards the mouse cursor’s position (ie. the reticule) upon pressing the spacebar. I am trying to accomplish this by using a raycast which can then return a position that I can hopefully instantiate the ball prefab towards. I’m pretty new to Unity so I’m not even sure that this is the right way to go about it. I did try to use Instantiate alone to fire from the camera towards the mouse cursor but couldn’t get it to work.

The relevant part of my script is below (I did have force added for colliding with rigid bodies amongst other things but I thought it best to minimise how much I pasted in here). When I hit play I can see the line for the raycast being drawn straight ahead from the camera so it does work. However, I’m not sure what to use to get the ray to fire towards the mouse position. I have tried making the rayDirection variable Input.mousePosition but this stops the line from being drawn.

Thanks in advance for any advice and here is the stripped down version of the script which just draws a line straight from the camera. I need to know whether it’s possible to adapt this to go towards the current mouse position:

// Declare variables
var rayRange:int = 1000;

	function Update () {
	
		if(Input.GetKeyDown(KeyCode.Space)){
		
			FireRay();
		
		}
	
	}
	
// Define functions

function FireRay(){

	var rayDirection = transform.forward;
	
		Debug.DrawRay(transform.position, rayDirection * rayRange, Color.cyan);

}

the mouses position is

Input.mouseposition
Thats it, unity knows it for you.

to find the direction from the camera to the mouse.
its where your going - where your coming from.

Direction = Input.mouseposition(the to) - camera.transform.position(the from)


ray.origin = camera.transform.position
ray.direction = direction (see calculation above)

But you dont actually want to cast a ray.

You want the direction from camera to mouse which I already told you how to find
so spawn from camera with it heading towards direction.

best of luck and mark as answered!