rotating character around mouse

Hi! i am trying to make my character face the mouse position doing:

var to : Vector3 = Vector3( Input.mousePosition.x -Screen.width /2 ,0, Input.mousePosition.y -Screen.height/2 );

var rot : Quaternion = Quaternion.LookRotation(to, Vector3.up);

transform.rotation =rot;

this works if the character is at the origin, but if he moves around it does not. I have tried everything i can think of to make it work ok, but i can't.

I know i have to take into account the character position also but whatever i do it doesn't work ok. Could you help me?


EDIT: bugfix: `to` changed to `to - transform.position`.

Disclaimer, as I type code here without testing it in unity there are probably errors in it but the concept should hold:

var distanceFromCamera : float = 100.0; // how far is the camera away from the ground

function Update() {
    var to : Vector3 = Camera.main.ScreenToWorldPoint(Input.mousePosition.x, Input.mousePosition.y, distanceFromCamera);
    var rot : Quaternion = Quaternion.LookRotation(to - transform.position, Vector3.up);
    transform.rotation =rot;

The basic idea is that you have to find a real-world coordinate where your mouse is aiming at. For this example the distance from the Camera to the ground should be constant and must be correctly defined in the `distanceFromCamera` var to have code work. If you have a sloped terrain or camera isn't looking straight down the best way to find the world point is by putting the terrain separate layer (say layer: Terrain), use `Camera.ScreenPontToRay` and a `Physics.Raycast` with layermask set to Terrain layer.

Thanks Jaap, i finally went another way, it works fine but don't know if it is right.

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

	var hits : RaycastHit[];
	hits = Physics.RaycastAll (ray);

	for (var i=0;i<hits.length;i++)
		if(hits.length >0)
			var hit : RaycastHit = hits*;*
*			var trans = hit.point;*
*			transform.LookAt(Vector3(trans.x,5,trans.z),Vector3.up);				*
*		}*
*	}*

Attention please. I’ve got the best and easiest solution. Just create a very small cube and make it your character’s child and place it inside the character . Apply smooth orbit to the camera and give the cube its target. Now the camera will follow and orbit the box and also character. Now what is left is rotating the character with mouse. In the script applied to character,

In function awake
var cam : Transform;

in the inspector give the camera object to the variable cam.
write in function update

transform.eulerAngles = Vector3 (0,cam.transform.eulerAngles.y , 0);

This will do the job without any chaos like stuff. Its very easy.