GameObject follow the mouse

I need to have a GameObject follow the mouse on the screen perfectly, and move flatly (see image below). The camera can be pretty much any angle, so right, forward, and up may be different at any given time.

This code works, except it causes the gameobject to move in a radius around the camera, instead of making it look like it is at a consistent depth away from the camera (the model looks like it gets bigger around the edges of the camera).

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
gameobject.transform.position = ray.GetPoint(5);

How would I go about doing this?


Currently, if the camera is looking straight at the model, the green is how the model is currently moving relative to the camera, the white dot. The white lines is the camera projection. The red line is how the model should move. No matter the angle of the camera, the model should be moving in a flat plane relative to the camera, instead of the radius arc that is done with the code above.

So how would I dynamically calculate the radius from the camera to make sure the model moves on a flat plane relative to the camera??


adapted from the angrybots sample-

call CalcDesiredMoveTargetFromMouse when you want the player to start moving towards the mouse ( probably in your Update function, or when the mouse is clicked, depending on whether you want to only do this at mouse click ) and then set your game object’s transform to mDesiredWorldPosition however you want ( smoothly or immediately, etc )

Vector3 GetPlaneRayIntersection ( Plane inPlane, Ray inRay )
	float dist;
	inPlane.Raycast( inRay, out dist );
	return inRay.GetPoint( dist );
Vector3 ScreenPointToWorldPointOnPlane ( Vector3 inScreenPoint, Plane inPlane, Camera inCamera ) 
	// Set up a ray corresponding to the screen position
	Ray ray = inCamera.ScreenPointToRay( inScreenPoint );
	// Find out where the ray intersects with the plane
	return GetPlaneRayIntersection( inPlane, ray );
void CalcDesiredMoveTargetFromMouse()
	Vector3 cursorScreenPosition = Input.mousePosition;
	//should we build a plane around where the character
	Transform myTransform = GetComponent< Transform >();
	Plane playerMovementPlane = new Plane( myTransform.up, myTransform.position );
	mDesiredWorldPosition = ScreenPointToWorldPointOnPlane( cursorScreenPosition, playerMovementPlane, Camera.mainCamera );
	mHasDesiredWorldPosition = true;		

//apply this on object that you want to move with mouse

function Update() {
   pos = Input.mousePosition;
   pos.z = cube.transform.position.z- mainCamera.transform.position.z;
   transform.position = mainCamera.ScreenToWorldPoint(pos);

//try it i hope it will work.

There are some ways…

  1. is to get crossproduct of camerapos, gamobject pos, and gameobject.up. then project your ray to cross product; (ray intersection point)

  2. create a plane representing yout gameobject, and move along it