Mouse aims at object ?

Hi all,

How to map mouse position on screen to world position ?

I know that this question has been asked a lot, but i have a problem.

In my game i display a crosshair instead of the mouse cursor for the player to aim. When “Fire” is clicked i want to instantiate a sphere(the missile i use) at a position relative to the cursor’s position.

I tried Raycast, but it don work as i want it to be. This is almost close to what i want to achieve.

I use the following code:

	// get the position of the mouse
	var mousePos : Vector3 = Input.mousePosition;
	var mouseToWorld : Vector3 = Camera.main.ScreenToWorldPoint (Vector3(mousePos.x , mousePos.y, Camera.main.nearClipPlane));
	// instantiate a new object of the type of the missile
	var instantiatedProjectTile : Rigidbody = Instantiate(projectTile, mouseToWorld, Quaternion.identity);
	// adjust the velocity of the missle in the Z direction
	instantiatedProjectTile.velocity = transform.TransformDirection(Vector3(0, 0, speed));

But it don work properly, the spheres don go in the direction of the object the cursor was aiming at.

P.S: I am using a Terrain as my playground.

Any help is appreciated,

Thanks,

Samer

When you instantiate them you want them not to give a rotation of Quaternion.identity but the rotation of the camera±

Instantiate( ..., ..., Camera.main.transform.rotation);

Then the velocity you want to give it is simply a local forward one

...velocity = instantiatedProjectile.transform.forward * magnitude

where magnitude is the magnitude of the velocity you want to give it.