C# 触摸控制单元2D

C# 触摸控制单元2D,c#,unity3d,C#,Unity3d,我正在尝试使用触摸控件在iPhone等设备上移动我的角色。到目前为止,我的成功有限。此代码可以工作,但仅适用于其中一个按钮。我有一个左键和右键,左键一直工作到我添加了右键。现在只有右边的按钮起作用了。任何帮助都将不胜感激 foreach (Touch touch in Input.touches) { if(leftButton.guiTexture.HitTest(touch.position) && touch.phase != TouchPhase

我正在尝试使用触摸控件在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;
            }

    }

一种更简单的点击方法是

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

请记住更改可单击对象(我认为是触摸)的输入。

首先,进行健全性检查,并验证组件上的左右按钮设置正确

我目前并没有在一台使用unity的计算机上测试所有东西,但是这里有很多冗余,我们可以清理它以使调试问题更容易。另一个危险信号是,在输入检查之前,我没有看到move被设置为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触摸另一个按钮,我假设这意味着您希望没有移动?)

我相信是这样,但您可能需要先创建一个可单击的对象,而不是gui。所以回过头来看,它似乎不那么可行。如果有人想纠正我,请随意。如果您没有得到答案,请尝试发布到unity answers。如果您想简单地使用GUI,您可以使用它:即获取鼠标位置(在屏幕坐标中),然后根据其位置和大小简单地测试它是否在GUI对象的矩形内。您如何检查按钮是否工作?在这两种情况下,您都将动画参数
Speed
设置为
1