Having player object always snap to mouse position

I’m making a scrolling shooter that can be controlled by only using the mouse. This game required the player to be able to move the player with the mouse; the player’s position is locked to the mouse’s position for this game.

I recently found a script which allows the player to drag objects around when the mouse is over them and the player holds the mouse button down.

Vector3 screenPoint;
    Vector3 offset;

    void OnMouseDown()
        screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);

        offset = gameObject.transform.position - 
            Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));


    void OnMouseDrag()
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);

        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) - offset;
        transform.position = curPosition;


However, I need the player to also shoot projectiles when clicking the left mouse button down. Is there a way to set the player’s position to always be the mouse’s position without having the player holding down the LMB to snap the player object to the mouse position?

As always, any help would be appreciated. Thank you for taking the time to read this message.

You need to do your calculations inside Update() rather than OnMouseDown(). This code assumes that your camera is axes aligned and is looking towards positive ‘z’. Here is a bit of code to demonstrate:

#pragma strict

private var dist : float;

function Start() {
	dist = transform.position.z - Camera.main.transform.position.z;

function Update() {
	var pos = Input.mousePosition;
	pos.z = dist;
	transform.position = Camera.main.ScreenToWorldPoint(pos);

This code will work for both a perspective and an orthographic cameras.