Making a hand move with the mouse

Hey everyone, first time posting so sorry if I’m in the wrong spot. I’m trying to make a part of a game that involves moving a hand over a table in a 3D environment with the mouse similar to how Surgeon Simulator’s controls operate. (Minus the finger movements). I’m pretty new to working in 3D and I’ve tried a few different ways I thought would make this work but I’m completely lost. If anyone could help point me in the right direction, I would really appreciate it,


You need to:

  1. Find the camera position

  2. Find the mouse click direction

  3. Find unknown variable t in the formula: camPos + t*dir = intersectionPoint

If you define your table to be in the XY-plane, you will know the z-value of the intersectionPoint. If the table is positioned at z=0, you get: camPos.z = t*dir.z = 0, which makes the caluclation easy.

Code, with comments:

using UnityEngine;
using System.Collections;

public class MouseMovement : MonoBehaviour {

	// Use this for initialization
	void Start () {
	// Update is called once per frame
	void Update () {

        // We set our "table" to be at the XY-plane.
        float tableZ = 0.0f; // Our "table" is positoned at Z = 0. You may change this.

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

        Vector3 camPos = ray.origin;
        Vector3 mouseDir = ray.direction; // direction from camera centre towards mouse position.
                                          // .. along this vector, every point is visibly hidden behind the mouse.

        // We have origin "camPos" and direction "mouseDir". We want to find the point where this ray intersects the XY-plane at Z = tableZ
        // camPos + t*mouseDir = intersPos,  where t and intersPos are unknown
        // We know that intersPos.z = tableZ
        // => camPos.z + t*mouseDir.z = tableZ
        // => t = (tableZ - camPos.z) / mouseDir.z
        float t = (tableZ - camPos.z) / mouseDir.z;
        Vector3 intersPos = camPos + t*mouseDir; // original formula: camPos + t*mouseDir = intersPos

        transform.position = intersPos;


Here is a link to my test project:
I made it using Unity version 5.3.3

Note: You may change the value of tableZ, depending on where your table is positioned.
Also, if your table is not positioned at the XY-plane, you only change the formula slightly, by using the x-value or y-value instead.