- Home /
Mouse won't freeze in center of screen
Hi I am very very new to both unity and javascript. I am using this code to apply a custom cursor to the mouse (a cross hair) and then freeze the mouse to the center of the screen. However it only partially works, the cursor applies just fine and it locks to the screen it just doesn't lock to the center of the screen like I need so it can click on stuff. If anyone knows a good way to do this or a way to fix my code, that would be awesome! Here is what I've come up with so far.
Screen.lockCursor = true;
var cursorTexture : Texture2D;
var cursorMode : CursorMode = CursorMode.Auto;
var hotSpot : Vector2 = Vector2.zero;
function Update () {
// In standalone player we have to provide our own key
// input for unlocking the cursor
if (Input.GetKeyDown ("escape"))
Screen.lockCursor = false;
Cursor.SetCursor(cursorTexture, hotSpot, cursorMode);
}
Thanks for any help!
Answer by Spoink · Feb 26, 2014 at 05:45 PM
To lock the cursor can be a bit tricky. I've noticed that the Screen.lockCursor wont lock the cursor but move it back to center, leading the mouse to jump around when doing extreme mouse movements.
What I do when I want to make an FPS is to lock the cursor and hide it. Then I do all the gui and hit checks from center of screen. This removes all issues with the mouse.
I only code in C#, but here is what I would do if I were to make a simple shooter.
private bool isShowingMouse = true;
void Start()
{ ToggleMouse(false); }
void Update()
{
if(Input.GetMouseButtonDown(0))
{ Fire(); }
if(Input.GetKeyDown(KeyCode.Escape))
{ ToggleMouse(!this.isShowingMouse); }
}
private void ToggleMouse(bool showMouse)
{
Screen.lockCursor = !showMouse;
Screen.showCursor = showMouse;
this.isShowingMouse = !this.isShowingMouse;
}
private void Fire()
{
Transform cameraTransform = Camera.main.transform;
Ray fireRay = new Ray(cameraTransform.position, cameraTransform.forward);
RaycastHit hit;
if(!Physics.Raycast(fireRay, out hit))
{ return; }
Debug.Log("Hit: " + hit.collider.name);
}
And then you just rotate the camera based on the delta movements from the mouse input. Fyi, I did not test the code, so it might not work directly, but you get the idea :)
Thanks so much! I don't know C# but honestly I don't know javascript either, something weird though, the mouse still doesnt center in unity but when I play the stand alone it does. Any idea why that might be?