Touch Controls Unity2D

时间:2014-05-18 16:34:35

标签: c# unity3d

我试图使用触控来移动我的角色在iPhone等设备上。到目前为止,我的成功有限。此代码有效,但仅适用于其中一个按钮。我有左右按钮,左按钮一直工作,直到我添加了右键。现在只有右键有效。任何帮助将不胜感激。

foreach (Touch touch in Input.touches)
    {

        if(leftButton.guiTexture.HitTest(touch.position) && touch.phase != TouchPhase.Ended)
            {
                move = -1;
                anim.SetFloat ("Speed", Mathf.Abs (move));

            }
        else if(rightButton.guiTexture.HitTest(touch.position) && touch.phase != TouchPhase.Ended)
            {
                move = 1;
                anim.SetFloat ("Speed", Mathf.Abs (move));
            }
        else if((leftButton.guiTexture.HitTest(touch.position) && touch.phase == TouchPhase.Ended) && 
                (rightButton.guiTexture.HitTest(touch.position) && touch.phase == TouchPhase.Ended))
            {
                move = 0;
            }

    }

2 个答案:

答案 0 :(得分:0)

点击的更简单的替代方法是

if(Input.GetMouseButtonDown(0))
{
    //Your stuff here
}

记得更改可点击对象的输入(我认为是触摸)

答案 1 :(得分:0)

首先,进行完整性检查并确认组件上的左右按钮设置正确。

我目前没有使用统一的计算机来测试所有内容,但这里有很多冗余,我们可以将其清理干净,以便更轻松地调试问题。另一个红旗是我在输入检查之前看不到移动被设置为0,所以我将添加它。试试这段代码,看看你是否还在看问题,也许你可以用monodevelop更好地调试发生的事情。

move = 0;
bool isLeftPressed = false;
bool isRightPressed = false;

foreach (Touch touch in Input.touches)
{
    // Only process touches that aren't in the ended phase
    if (touch.phase == TouchPhase.Ended)
        return;

    if (leftButton.guiTexture.HitTest(touch.position))
        isLeftPressed = true;

    if (rightButton.guiTexture.HitTest(touch.position))
        isRightPressed = true;
}

if (isLeftPressed && isRightPressed)
{
    // Do nothing when both are pressed (move already set to 0)
}
else if (isLeftPressed)
{
    move = -1;
}
else if (isRightPressed)
{
    move = 1;
}

anim.SetFloat ("Speed", Mathf.Abs (move));

我做了一些关于你试图做什么的假设,如果左右都按下了。我们只是设置标志,而不是在foreach循环中设置移动值,以便在处理完每个触摸后我们可以看到正在按下哪些按钮(如果手指0正在触摸另一个,而手指1正在触摸另一个,我认为这意味着你希望没有运动?)