Fire at mouse position, fps

I have been searching for this solution and I am having trouble understanding them. I have a first person camera that does not move or rotate. I want the player to be able to click on the screen and an object will be launched in that direction. Not a bullet but a ball.

Hi, i found this qn interesting so made a small script.
I used a raycast to find the world vector you’re clicking on, and instantiating a sphere there.

So make a new scene.

In Hierarchy, create a Cube, centre 0;0;0 , scale x:50; y:0.05; z:50 .

Rename this cube Floor.

In Hierarchy, create a Sphere, centre 0;0;0 , scale x:0.25; y:0.25; z:0.25 .

In Project, create a Prefab, drag the Sphere into this prefab , then delete the Sphere from Hierarchy .

In Project, create a Script, and attach it to the main Camera in Hierarchy.

In the script , paste this code :

// Click for Object name and position script
// ----

var rayHitWorldPosition : Vector3;
var objectClickedName : String;
var objectClickedPosition : Vector3;
var objBall : Transform;

// ----

function FixedUpdate()
	// get player input		
		if (Input.GetKeyDown(KeyCode.Mouse0))
			// raycast
			var rayHit : RaycastHit;
			if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), rayHit))
				// where did the raycast hit in the world - position of rayhit
				rayHitWorldPosition = rayHit.point;
					print ("rayHit.point : " + rayHit.point + " (rayHitWorldPosition)");
				objectClickedName =; // name of rayHit's collider
					print ("objectClickedName : " + objectClickedName);
				objectClickedPosition = rayHit.collider.gameObject.transform.position; // position of rayHit's collider
					print ("objectClickedPosition : " + objectClickedPosition);
				if (objectClickedName == "Floor")
					Instantiate (objBall, rayHit.point, Quaternion.identity);

// ----

Finally , in Hierarchy, click on the main Camera, then drag and drop your Prefab Sphere into objBall (in the Inspector for main Camera).

Then Play the project. When you click on the scene, a Sphere should appear where you click on the Floor.

In the Console, there is some information popping up. For this to work , you need 2 things : the name of the collider you want the raycast to get it’s vector from; and the .point that the raycast hits.

For what you want, I would tell the ball where the raycast hit is, then the ball script can do it’s movement to that vector.

I’m new to programming and unity (well, 3 months now) so to all the pro’s, sry if this is a long-winded or poor explanation of the class :slight_smile: