- Home /
How to move the mouse position to the center of the screen?
Alright, so I am creating a camera script that rotates the camera based on the mouse movement, but you can also pick up items. What I want is to move the mouse (which moves the camera) but when you stop moving the mouse it lerps back to the center of the screen. Would this be possible in unity? And if so, How?
Answer by robertbu · Feb 13, 2014 at 08:44 PM
With Unity Pro, you might be able to reset the position of the hardware cursor through a plugin on some platforms. Typically this problem is solved (free and pro) by emulating the cursor and hiding the physical cursor. You create your own cursor, typically a GUITexture, and then you move it by the delta change in the cursor position. As an quick example (and there are other ways), attach this script to a GUI texture:
#pragma strict
var factor = 0.02;
function Update() {
var v = Vector3(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"), 0.0);
transform.position += v * factor;
transform.position.x = Mathf.Clamp01(transform.position.x);
transform.position.y = Mathf.Clamp01(transform.position.y);
if (Input.GetKeyDown(KeyCode.R)) {
transform.position = Vector3(0.5, 0.5, 0.0);
}
}
Hitting the 'R' key will center the GUITexture. Note that your aiming code will now have to start using the position of this game object rather than the position of the mouse. Also GUITextures use Viewport coordinates instead of Screen coordinates. I don't know how you are doing your aiming, but you will need Camera.ViewportPointToRay() or Camera.ViewportToWorldPoint() instead of the 'Screen' equivalents. Note this code does not hide the hardware mouse because I wanted you to see the mouse position vs. the graphic position. To hide the mouse see: Screen.ShowCursor().
Your answer
Follow this Question
Related Questions
Pickup Script, Lerping to position needs to stay. 0 Answers
How do I limit cursor movement? 1 Answer
Camera won't follow character 2 Answers