- Home /
Mecanim: move with mouse
Hey everyone, this is my first question and although I'm still a newbie at both JS/C# and Unity, I've learned a lot in the past few months, but lately I've been struggling with Mecanim implementation.
I have a character gameobject in a 3d plane and I want to move it/animate it with mecanim. To do that, I was thinking of using the mouse distance from the game object in any direction to determine the Speed parameter, and then the actual mouse coordinates in the X/Y axis to determine the Direction parameter.
The problem with this logic is that the mouse origin is relative to the screen's bottom left corner. Is there a way to make them relative to the character(so that mouse 0, 0 corresponds to the character's 0, 0)? If not, what other way could I move the character with the mouse using mecanim?
Hope that my question is clear enough, thanks in advance.
Answer by verenion · Jul 25, 2013 at 01:22 PM
Hey, This is a fairly straight forward thing to do. You need to calculate the difference between the mouse co-ords and the players position on the screen (2D vector). The WorldToScreenPoint function does most of the hard work
// get the position of the player's on screen coords
Vector3 screenPos = camera.WorldToScreenPoint(playerTransform.position);
Vector3 mousePos = Input.mousePosition;
// calculate the 'difference' between the two screen positions, you
// could use Vector3 functions to calculate the angle or something else if you needed it
Vector3 movementDelta = screenPos - mousePos;