unity3d触屏操作对象运动
using UnityEngine; using System.Collections; public class robot : MonoBehaviour { private GameObject myRobot; private Camera carmera; // Use this for initialization void Start () { myRobot = GameObject.Find("robot"); //carmera = Camera.main; //第二种方式去获取Camera //carmera = GameObject.Find("Main Camera").GetComponent<Camera>(); Input.multiTouchEnabled = true; } // Update is called once per frame void Update () { handInput(); } void handInput() { #if !UNITY_EDITOR && ( UNITY_IOS || UNITY_ANDROID ) mobileInput(); #else if (Input.GetKey(KeyCode.UpArrow)) { myRobot.transform.Translate(Vector3.forward * Time.deltaTime); } if (Input.GetKey(KeyCode.DownArrow)) { myRobot.transform.Translate(-Vector3.forward * Time.deltaTime); } if (Input.GetKey(KeyCode.LeftArrow)) { myRobot.transform.Translate(Vector3.left * Time.deltaTime); } if (Input.GetKey(KeyCode.RightArrow)) { myRobot.transform.Translate(Vector3.right * Time.deltaTime); } // float x = carmera.WorldToScreenPoint(myRobot.transform.position).x; // Debug.Log("x = " + x); #endif } void mobileInput() { if (Input.touchCount == 1) { if (Input.touches[0].phase == TouchPhase.Moved){ float x = Input.touches[0].position.x; float y = Input.touches[0].position.y; if (x > carmera.WorldToScreenPoint(myRobot.transform.position).x) { myRobot.transform.Translate(Vector3.right * Time.deltaTime); } else if (x < carmera.WorldToScreenPoint(myRobot.transform.position).x) { myRobot.transform.Translate(-Vector3.right * Time.deltaTime); } if (y > carmera.WorldToScreenPoint(myRobot.transform.position).y) { myRobot.transform.Translate(Vector3.forward * Time.deltaTime); } else if (y < carmera.WorldToScreenPoint(myRobot.transform.position).y) { myRobot.transform.Translate(-Vector3.forward * Time.deltaTime); } } } } }
1. 两种获取Camera方式。
2. 手机触屏操作,需要进行世界坐标转屏幕坐标。