大家好!我试图删除跳转按钮,并用触摸控件替换它,但是当我测试它时,脚本会将任何触摸都视为跳转。我的目标是仅在玩家触摸屏幕上除操纵杆以外的任何部分时才检测到它。有谁知道我将如何实现这一目标? 这是我的代码:
if(Input.GetButtonDown("Fire1"))
{
Rb.AddForce(Vector3.up * Jump);
}
答案 0 :(得分:0)
要忽略操纵杆的区域,您必须过滤触摸,而不要遍历所有Input.touches
并仅保留“有效”的触摸,使那些触摸变为
当前处于TouchPhase.Began
阶段
和不。假设Canvas
中有一个UI元素,您可以使用IsPointerOverGameObject(int)
传入触摸的fingerId
,如果触摸到任何UI元素,则返回true
。
要简化过滤,可以使用Linq Any
if(Input.touches.Any(touch => touch.phase == TouchPhase.Began && !EventSystem.current.IsPointerOverGameObject(touch.fingerId))
{
Rb.AddForce(Vector3.up * Jump);
}
在这里使用Any
基本上只是写作的捷径
foreach(var touch in Input.touches)
{
if(touch.phase == TouchPhase.Began && !EventSystem.current.IsPointerOverGameObject(touch.fingerId))
{
Rb.AddForce(Vector3.up * Jump);
break;
}
}
您可以根据需要扩展和完善条件。您可以例如也可以使用touch.position
来忽略屏幕特定区域的所有触摸,例如
if(Input.touches.Any(touch => touch.phase == TouchPhase.Began && touch.position.x > MIN_X && touch.position.y > MIN_Y && !EventSystem.current.IsPointerOverGameObject(touch.fingerId))
{
Rb.AddForce(Vector3.up * Jump);
}
在MIN_X
和MIN_Y
中,您定义了一个覆盖操纵杆的矩形