Always keep an object on mouse's position

Hey I need help moving an object using the mouse. Im trying to make an object snap to the mouse’s position and always stay attached to the mouse. Kinda like a cursor. Also i would like to keep the object from moving on the z axis. Heres the script:

function Update(){

var curzer = GameObject.Find(“Cursor”);

transform.position.z = 0;

// cast a ray from the mouse pointer

var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

var hit: RaycastHit;

if (Physics.Raycast(ray, hit)){

curzer.transform.position = hit.point; // place curzer at the hit point

transform.position.z = 0;

}

}

When I play the game, it does exactly what the script tells it to do. The object follows wherever the mouse is when there is a collision of the ray. How do i place the target object to the cursors position at the beginning of the game and stay until the end? Thanks a bunches :smiley:

Not sure exactly what you’re trying to do, but if you just want another object to snap to the mouse, you’d do the same thing you’re already doing with the curzer object.

If what you mean is you’re having gaps in coverage (i.e. when your mouse is not over some physics object, the cursor stays behind), you can make a Plane and do raycasting on that the same way you do it with Physics: plane.Raycast(ray, hit). The plane extends to infinity in all directions, so there will be no gaps.

Here’s a slightly altered example of that from a project of mine (it’s in C#, but everything is mostly the same anyway):

class TrackMouse {
    Plane hitplane = new Plane( Vector3.up, transform.position); //create new plane, 
                                       //facing up, at the script owner's position

    GameObject cursor = GameObject.Find("Cursor");

    void Update() {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //cast the ray

	    float distance;
	    if (hitplane.Raycast(ray, out distance)){ //"out" here is just C# syntax;
                                                  //this assigns the raycast result
                                                  //to the "distance" variable

            cursor.transform.position = ray.GetPoint(distance); //set the position
                                                            //of the cursor object.
        }
    }

}