Launch a projectile to position of mouse?

I’m working on a game with a camera that is looking down onto the scene and I am trying to get projectiles (such as rockets and bullets) to launch towards the position of the mouse whenever the mouse button is clicked. For some reason my code will launch a projectile but only in one direction (and not where the mouse is pointed).

I’m using a script from the projectile examples in the unify wiki.

/// This behavior script fires a projectile to the point the user clicked on. 

// Anything declared outside a function is visible and can be changed in the inspector 
var projectile : GameObject; 
var speed = 2; 
var autoDestroySeconds = 10; 

var fireRate = 1.0; 
private var nextFire = 0.0; 

function Update () { 
   // Fire a projectile when the user hits mouse! 
   if (Input.GetMouseButtonDown (0)  !Input.GetKey("q")  Time.time > nextFire) { 
      nextFire = Time.time + fireRate; 

      // The target position of the projectile is found by casting a ray from the camera with the mouse position. 
      // This gives us the point the user clicked on. 
      ray = Camera.mainCamera.ViewportPointToRay(Vector3(0.5, 0.5, 0.0)); 

      // (Note: We need to declare this variable, because it is modified inside Physics.Raycast) 
      var hit : RaycastHit; 
      if (Physics.Raycast (ray, hit)) { 
         target = hit.point; 
      } 
      else { 
         // If the user clicks outside any object, we assume the target is 1000 units in front of the camera! 
         target = (ray.origin + ray.direction * 1000); 
      } 
       
      // The direction the projectile should fly along is simply the offset between the target position and the launch position 
      direction = target - transform.position; 

      // Instantiate the projectile and its entire transform hierarchy 
      // (Note: We need to declare this variable because Instantiate can't tell which type it will return) 
      var instantiatedProjectile : GameObject = Instantiate (projectile, transform.position, Quaternion.FromToRotation (Vector3.forward, direction)); 
      // Give it an initial velocity 
      instantiatedProjectile.rigidbody.velocity = direction.normalized * speed; 
       
      // Destroy the projectile in a few seconds. 
      // Destroying the game object kills the game object 
      // with all components and its transform hierarchy. 
      Destroy (instantiatedProjectile, autoDestroySeconds); 
   } 
}

I’ve got a mesh with a mesh colider and the projectile (for now) is a a capsule with a capsule colider.

the way I understand it is that you need to use something like so:

if (Input.GetMouseButtonDown (0)) {
	var hit : RaycastHit; 
	if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),  hit, 100)) {
		// do something here
	}
}

You want ScreenPointToRay, not ViewportToRay.

Cheers.

ScreenPointToRay works much better. Thank you!