using UnityEngine;
using System.Collections;
public class DragObject : MonoBehaviour {
public GUIText message = null;
private Transform pickedObject = null;
private Vector3 lastPlanePoint;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Plane targetPlane = new Plane(transform.up, transform.position);
//message.text = "";
foreach (Touch touch in Input.touches) {
//获取屏幕被触碰位置的射线。
Ray ray = Camera.main.ScreenPointToRay(touch.position);
//沿着平面得到射线的位置
float dist = 0.0f;
//计算射线与这个平面的交点. Sets dist to distance along the ray where intersects
targetPlane.Raycast(ray, out dist);
//Returns point dist along the ray.
Vector3 planePoint = ray.GetPoint(dist);
//Debug.Log("Point=" + planePoint);
//True if finger touch began. If ray intersects collider, set pickedObject to transform
of collider object
if (touch.phase == TouchPhase.Began) {
//Struct used to get info back from a raycast
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray, out hit, 1000)) { //True when Ray intersects colider.
If true, hit contains additional info about where collider was hit
pickedObject = hit.transform;
lastPlanePoint = planePoint;
} else {
pickedObject = null;
}
//Move Object when finger moves after object selected.
} else if (touch.phase == TouchPhase.Moved) {
if (pickedObject != null) {
pickedObject.position += planePoint - lastPlanePoint;
lastPlanePoint = planePoint;
}
//Set pickedObject to null after touch ends.
} else if (touch.phase == TouchPhase.Ended) {
pickedObject = null;
}
}
}
}
把以上代码放在ARCamera下,让用户可以触碰拖拽物体,前提是这个物体需要有mesh collider.