move Game Object(hand) with mouse movement

hi guys,

i want to move my player's hand object with mouse cursor movements...can any one help me...i have googled past some hours, still i'm struggling to find the answer...

thank you..

You are moving a 3D world game object using a 2D input (mouse), so you need to decide how to handle the third axis. In this situation it sounds like you will want it to move on a 'virtual plane' aligned to the camera; so it is always the same distance away and moves on a 2d surface, parallel to the screen.

To do this we need to translate the cursor location from screen space (x&y on the screen) to world space (x,y,z in your game world). This is done by creating a Ray, like so:

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

This 'shoots' a ray from the position of the mouse, through the screen and into the game world. Well, you can think of it like that. Rays are infinite in length; what we want is a point along it. So we use:

var pos : Vector3 = ray.GetPoint(5);

This gets a 3d coordinate for a point on our ray, 5 units from the camera. You can adjust this as necessary, or better yet make it a variable.

We now have our position, so all we need to do is make the object in question use it every frame:

transform.position = pos;

Adding those three lines should be a good starting point to getting the behviour you want. Hope this helps.

With the above solution, the hand changes its height in the virtual world as you move the mouse up/down.

If instead you want to keep the hand at a stable height in the world, you can do this:

void Update() {
    // mouse wheel y moves hand to/from ground
    this.height += Input.mouseScrollDelta.y;
    // Don't go below ground
    this.height = Mathf.Max(this.height, 0);

    // Keep hand under mouse pointer, at stable world height
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    var heightPlane = new Plane(Vector3.up, new Vector3(0, this.height, 0));
    var distanceFromCamera = 0F;
    heightPlane.Raycast(ray, out distanceFromCamera);
    transform.position = ray.GetPoint(distanceFromCamera);
}