在移动设备上使用触摸输入控制播放器

Controlling a player using touch input on the mobile device

我是 Unity 的新手,正在学习滚球教程。
我是为移动和桌面创建它并且它正在工作但我遇到的唯一问题是我无法创建触摸键箭头(左,右,上,下)来控制触摸屏设备上的播放器。

请查看我下面控制播放器的代码:

 using UnityEngine;
 using UnityEngine.UI;
 using System.Collections;

public class PlayerController : MonoBehaviour {
public float speed;
public Text countText;
public Texture2D button1; //button 1
public Texture2D button2; //button2
public Texture texture;

private Rigidbody rb;
private int count;
// Use this for initialization
void Start () {
    Screen.orientation = ScreenOrientation.LandscapeLeft;
    //GUITexture.texture = button1;
    rb = GetComponent<Rigidbody> ();
    count = 0;
    SetCountText ();
}

// Update is called once per frame
void FixedUpdate () {
    Screen.orientation = ScreenOrientation.LandscapeLeft;
    Screen.sleepTimeout = SleepTimeout.NeverSleep;
    if (SystemInfo.deviceType == DeviceType.Desktop) {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");
        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
        GetComponent<Rigidbody>().AddForce (movement * speed * Time.deltaTime);
        if (Input.GetKey("escape"))
        {
            Application.Quit();
        }

    }//END Desktop
    else 
    {
        float moveHorizontal = Input.acceleration.x;
        float moveVertical = Input.acceleration.y;
        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
        GetComponent<Rigidbody>().AddForce (movement * speed * Time.deltaTime);
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Application.Quit(); 
        }
        foreach(Touch touch in Input.touches)
        {
            //Always getting error here
            if (GUITexture.HitTest(touch.position) && touch.phase !=TouchPhase.Ended)
            {
                GUITexture.texture = button2;
                transform.Translate(Vector3.right*30*Time.smoothDeltaTime);
            }else if(GUITexture.HitTest(touch.position) && touch.phase !=TouchPhase.Ended)
            {
                GUITexture.texture = button1;
            }
        }
    }
    // Building of force vector 

}

void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag ("Pick Up"))
    {
        other.gameObject.SetActive(false);
        count = count + 1;
        SetCountText();
    }
}
void SetCountText()
{
    countText.text = "Count:" + count.ToString ();

}
}

您尝试像静态函数一样从 GUITexture 直接调用 HitTestHitTest 不是静态函数,您需要从 GUITexture 创建一个变量class 然后从该对象调用 HitTest 函数,如下所示:

public GUITexture guiT;

if (guiT.HitTest(touch.position) && touch.phase !=TouchPhase.Ended)
{
    guiT.texture = button2;
    transform.Translate(Vector3.right*30*Time.smoothDeltaTime);
}
else if(guiT.HitTest(touch.position) && touch.phase !=TouchPhase.Ended)
{
    guiT.texture = button1;
}  

不要忘记将 guiT 变量分配给编辑器中的内容。