新建一个plane物体,tag设为Terrain,新建一个Cube物体,添加Rigidbody组件,tag设为Player,创建一个脚本TouchTest02,将该脚本挂到Cube物体上。本示例实现如下效果:当单击触摸屏时Cube移动到指定位置,当双击Cube时,Cube跳跃。脚本代码如下:
- using UnityEngine;
- using System.Collections;
- using UnityEngine.UI;
- public class TouchTest02 : MonoBehaviour
- {
- private Rigidbody m_rigidbody;
- public Text tip;
- void Awake()
- {
- Input.multiTouchEnabled = true;
- m_rigidbody = GetComponent<Rigidbody>();
- }
- void Update()
- {
- int touchNum = Input.touchCount;
- if (touchNum > 0)
- {
- Touch touch = Input.GetTouch(0);
- if (touch.phase == TouchPhase.Began)
- {
- RaycastHit hit;
- Ray ray = Camera.main.ScreenPointToRay(touch.position);
- bool isHit = Physics.Raycast(ray, out hit);
- if (touch.tapCount == 1)
- {
- if (isHit)
- {
- if (hit.collider.tag == "Terrain")
- {
- transform.position = new Vector3(hit.point.x, hit.point.y + 0.5f, hit.point.z);
- }
- }
- }
- else
- {
- if (touch.tapCount == 2)
- {
- if (isHit)
- {
- if (hit.collider.tag == "Player")
- {
- m_rigidbody.AddForce(Vector3.up * 300f);
- tip.text = touch.tapCount.ToString();
- }
- }
- }
- }
- }
- }
- }
- }