您的位置:首页 > 移动开发 > Unity3D

Unity3D之触摸输入实现在指定地形上拖拽物体

2015-05-15 20:52 218 查看
新建一个Plane物体,tag设为Terrain,新建一个Cube物体,创建一个脚本TouchTest03,将该脚本挂载到Cube上,代码如下:

using UnityEngine;
using System.Collections;

public class TouchTest03 : MonoBehaviour
{
private bool isSelect;
private bool isDrag;

void Awake()
{
isSelect = false;
isDrag = false;
}

void Update()
{
int touchNum = Input.touchCount;

if (touchNum > 0)
{
Touch touch = Input.GetTouch(0);
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(touch.position);
bool isHit = Physics.Raycast(ray, out hit);
switch (touch.phase)
{
case TouchPhase.Began:
if (isHit)
{
if (hit.collider.gameObject == this.gameObject)
{
isSelect = true;
}
}
break;

case TouchPhase.Moved:
isDrag = true;
break;

case TouchPhase.Ended:
case TouchPhase.Canceled:
isDrag = false;
isSelect = false;
break;

default:
break;
}

if (isSelect && isDrag)
{
if (hit.collider.tag == "Terrain")
{
transform.position = new Vector3(hit.point.x, hit.point.y + 0.5f, hit.point.z);
}
}
}
}
}
OK,完成!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐