How to stop movement, when mouse is off screen

后端 未结 3 1112
夕颜
夕颜 2021-01-22 21:03

I\'m hoping there\'s someone out there that can help me with a small problem.

Currently I have an Input Manager attached to the main camera to allow the user to pan arou

相关标签:
3条回答
  • 2021-01-22 21:39

    3 Ideas:

    Rect screenRect = new Rect(0,0, Screen.width, Screen.height);
    if (!screenRect.Contains(Input.mousePosition))
        return;
    

    The same can be written more verbously as:

    float mouseX = Input.MousePosition.x;
    float mouseY = Input.MousePosition.y;
    float screenX = Screen.width;
    float screenY = Screen.height;
    
    if (mouseX < 0 || mouseX > screenX || mouseY < 0 || mouseY > screenY)
        return;
    
    // your Update body
    

    ...which is pretty much the same as your "hacky" solution (which is completely valid imho).

    Another option is to create 4 Rect objects for each screen border, then check if mouse is inside those rects. Example:

    public float boundary = 50;
    public float speed = 4;
    private Rect bottomBorder;
    private Rect topBorder;
    private Transform cameraTransform;
    
    private void Start()
    {
        cameraTransform = Camera.mainCamera.transform
        bottomBorder = new Rect(0, 0, Screen.width, boundary);
        topBorder = new Rect(0, Screen.height - boundary, Screen.width, boundary);
    }
    
    private void Update()
    {
        if (topBorder.Contains(Input.mousePosition))
        {
            position.y += speed * Time.deltaTime;
        }
    
        if (bottomBorder.Contains(Input.mousePosition))
        {
            position.y -= speed * Time.deltaTime;
        }
    
        cameraTransform.position = position;
    }
    

    The tricky part here is that Rect coordinates have Y axis pointing down and Input.mousePosition has Y pointing up... so bottomBorder Rect has to be on the top, and topBorder has to be at the bottom. Left and right borders are not affected.

    0 讨论(0)
  • 2021-01-22 21:49

    Due to the way Unity and the various host operating systems interact, you have limited control of the mouse cursor. (in short the OS controls the mouse Unity just reads it) That being said you do have some options. Screen.lockCursor jumps to mind.

    http://docs.unity3d.com/Documentation/ScriptReference/Screen-lockCursor.html

    It won't do exactly what you are looking for but it might be a good starting point

    0 讨论(0)
  • 2021-01-22 21:53

    Time.speed = 0;

    is this what you want?

    0 讨论(0)
提交回复
热议问题