Unity3D之触摸输入单击与双击研究

新建一个plane物体,tag设为Terrain,新建一个Cube物体,添加Rigidbody组件,tag设为Player,创建一个脚本TouchTest02,将该脚本挂到Cube物体上。本示例实现如下效果:当单击触摸屏时Cube移动到指定位置,当双击Cube时,Cube跳跃。脚本代码如下:

[csharp]  view plain copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3. using UnityEngine.UI;  
  4.   
  5. public class TouchTest02 : MonoBehaviour   
  6. {  
  7.     private Rigidbody m_rigidbody;  
  8.     public Text tip;  
  9.   
  10.     void Awake()  
  11.     {  
  12.         Input.multiTouchEnabled = true;  
  13.         m_rigidbody = GetComponent<Rigidbody>();  
  14.     }  
  15.   
  16.     void Update()  
  17.     {  
  18.         int touchNum = Input.touchCount;  
  19.   
  20.         if (touchNum > 0)  
  21.         {  
  22.             Touch touch = Input.GetTouch(0);  
  23.             if (touch.phase == TouchPhase.Began)  
  24.             {  
  25.                 RaycastHit hit;  
  26.                 Ray ray = Camera.main.ScreenPointToRay(touch.position);  
  27.                 bool isHit = Physics.Raycast(ray, out hit);  
  28.                 if (touch.tapCount == 1)  
  29.                 {  
  30.                     if (isHit)   
  31.                     {  
  32.                         if (hit.collider.tag == "Terrain")  
  33.                         {  
  34.                             transform.position = new Vector3(hit.point.x, hit.point.y + 0.5f, hit.point.z);  
  35.                         }  
  36.                     }  
  37.                 }  
  38.                 else  
  39.                 {  
  40.                     if (touch.tapCount == 2)  
  41.                     {  
  42.                         if (isHit)  
  43.                         {  
  44.                             if (hit.collider.tag == "Player")  
  45.                             {  
  46.                                 m_rigidbody.AddForce(Vector3.up * 300f);  
  47.                                 tip.text = touch.tapCount.ToString();  
  48.                             }  
  49.                         }  
  50.                     }  
  51.                 }  
  52.             }  
  53.         }  
  54.     }  
  55. }  

OK,完成!
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值