Look Vector of Mouse

I know this question has been asked before but I’m having an issue in my case that I cannot solve. I’m attempting to make a laser gun that shoots out where the user clicks on the screen. Part of the issue is that the laser is instantiated from one script, while the movement is handled in another one. I check for a mouse click(among other things) which does this:

Instantiate(laserPrefab, shootFX.transform.position, Quaternion.identity);

That shoots it originating at the tip of the gun, and then in the laser script that’s generated I have:

	void Update ()
    {
        transform.position += transform.forward * speed * Time.deltaTime;
    }

Now obviously that’s written so it goes in a straight line, but that is not what I’m trying to accomplish. I tried a few other things, like creating a vector3 inside the laser with the mouses position and traveling in that direction, but I couldn’t get it to work.

Well, so it’s a 3rd person game and the user actually have a mouse cursor and points to the place where you want to shoot. It however sounds a bit strange when you say “The shootFX is the tip of the gun, which does not move”. Doesn’t your character rotate and look in a certain direction? If the shootFX is a child of the gun and the gun a child of the character it would move and rotate with the character…

Anyways, you usually need those steps:

  • Create a ray from the camera along the mouse position. For this you simply use ScreenPointToRay with the current mousePosition.
  • Use Physics.Raycast and determine the world space hit point where your mouse is over.
  • Subtract your starting position from the hit point to get a direction vector.
  • Use Quaternion.LookRotation() to create the proper rotation which you can pass to Instantiate.

Something like that:

// inside Update
if (Input.GetMouseDown(0))
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit))
    {
        Vector3 pos = shootFX.transform.position;
        Vector3 dir = hit.point - pos;
        Instantiate(laserPrefab, pos, Quaternion.LookRotation(dir));
    }
}

That’s just an example.