- Home /
Is it possible to not allow the in-game cursor through certain sprites?
Hi, I want know if it's possible to restrict the in-game mouse position as if the mouse had a collider. You see the rectangular sprites in my photo? If a player tries to pass through them with his mouse, the mouse will be blocked and he has to go around it. The same effect if you have one monitor and you try to get the mouse out of the Window of the monitor. I tried restricting the Input.MousePosition
from screen point to worldView, but it is read only. Thank you for your time!
Answer by Ymrasu · Mar 17, 2019 at 09:43 PM
The mouse position is read-only. Though you could fake it by hiding and locking the cursor to your game window, then make a UI sprite (a custom cursor) follow the delta movement of the mouse. Something like this could help you get started:
public class CustomCursor : MonoBehaviour
{
// How fast the mouse moves, should use a slider for the player to adjust
public float mouseSensitivity = 150;
void Start()
{
// This hides and locks the mouse to the center of the screen
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
var mouseDelta = new Vector3(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")) * mouseSensitivity;
var targetPos = transform.position + mouseDelta;
// check for collision here and adjust targetPos
// if (mouseCollision) {
//
// }
// clamp custom mouse cursor to the screen
targetPos.x = Mathf.Clamp(targetPos.x, 0, Screen.width);
targetPos.y = Mathf.Clamp(targetPos.y, 0, Screen.height);
// set final position to the cursor
transform.position = targetPos;
}
}
Note that you'll want a way to lock and unlock the mouse from your game by the player (such as pressing ESC to toggle).
Your answer
Follow this Question
Related Questions
Restricting the mouse cursor from entering a certain area 0 Answers
Game runs fine, build fails(error returs 395). 0 Answers
SetCursor is not a member of Cursor 1 Answer
Teleport Not Working in Unity 2D 1 Answer
Gameobject follow cursor 2D 0 Answers