【问题标题】:How to make Input.GetAxis("Mouse X") get a value even when the mouse is stopped?即使鼠标停止,如何使 Input.GetAxis("Mouse X") 获取值?
【发布时间】:2019-05-14 15:13:01
【问题描述】:

我正在使用鼠标水平控制一个游戏对象。对象根据鼠标位置向左或向右移动,但一旦鼠标停止移动,对象也会停止。我想要的是,如果我将鼠标拖动到屏幕的右侧并停止移动鼠标,那么只要鼠标在屏幕的右半部分,我希望对象向右移动,反之亦然。当前 Input.GetAxis("鼠标 X");停止时返回 0 值。代码如下:

float horizontalInput = Input.GetAxis("Mouse X");

我已经尝试使用此修复程序,但我没有得到想要的结果,因为我使用 mousebuttondown 将我的播放器向前移动。

if (Input.GetMouseButton(0) && (horizontalInput == 0f))
{
    if (Input.mousePosition.x < Screen.width / 2)
    {
        horizontalInput = -1f;  
    }
    else if (Input.mousePosition.x > Screen.width / 2)
    {
        horizontalInput = 1f;
    }
}

还有其他方法可以实现吗?非常感谢您的宝贵时间!

我通过调整上面的 if 条件来修复它!

if (Input.GetMouseButton(0))
{
    if (Input.mousePosition.x < Screen.width / 2 && (horizontalInput < 0f))
    {
        horizontalInput = -1f;
    }
    if (Input.mousePosition.x > Screen.width / 2 && (horizontalInput > 0f))
    {
        horizontalInput = 1f;
    }             
}

【问题讨论】:

  • Input.mousePosition?
  • 你的意思是像 if(Input.mousePosition.x
  • 我通过更改 if 条件来检查左右移动的水平输入是大于还是小于 0 来修复它!

标签: c# unity3d


【解决方案1】:

只要检查horizo​​ntalInput而不是0并每次存储最后一个位置(每次都覆盖它)。 当它为 0 时,检查最后存储的位置,如果它在右侧,则继续移动对象,直到水平输入为 0 或到达屏幕边缘。 当然在Update中你甚至不需要循环一段时间,你只需要检查horizo​​ntalInput是0还是不是0。

类似这样的:

float horizontalInput = Input.GetAxis("Mouse X");
float lastPos = 0f;
if(horizontalInput  != 0){
  //move object with the mouse the code you currently use
  lastPos = Input.mousePosition.x;
}else if(horizontalInput == 0 && !EndOfScreen(currentObjectPos.x) && RighLeftScreen(lastPos)){
  Move();
}

当然这只是伪代码。您需要编写一个函数来知道 EndOfScreen 是从右还是左,您需要知道您是在屏幕的右侧还是左侧(RighLeftScreen 方法),最后您需要将对象向左或向右移动到最后屏幕。

这只是基本概念。

【讨论】:

  • 感谢您的解决方案!我做了类似的事情并通过更改 if 条件来检查左右移动的水平输入是否大于或小于 0 来修复它!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-17
相关资源
最近更新 更多