unity 觸屏程式碼(三)拖拽
private Vector3 screenPoint;
private Vector3 offset;
private bool isDwon = false;
private GameObject curGameObject;
void Start()
{
}
void Update()
{
if (Input.touchCount == 1)
{
if (isDwon)
{
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);//從攝像機發出到點選座標的射線
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
Debug.DrawLine(ray.origin, hitInfo.point, Color.red);//劃出射線,在scene檢視中能看到由攝像機發射出的射線
curGameObject = hitInfo.collider.gameObject;
Debug.Log(hitInfo.collider.gameObject.name);
}
else
{
curGameObject = null;
}
}
//開始按下
if (Input.GetTouch(0).phase == TouchPhase.Began)
{
if (curGameObject != null)
{
screenPoint = Camera.main.WorldToScreenPoint(curGameObject.transform.position);
offset = curGameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.GetTouch(0).position.x, Input.GetTouch(0).position.y, screenPoint.z));
isDwon = false;
}
}
//拖動物體
if (Input.GetTouch(0).phase == TouchPhase.Moved)
{
if (curGameObject != null)
{
Vector3 curScreenPoint = new Vector3(Input.GetTouch(0).position.x, Input.GetTouch(0).position.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
curGameObject.transform.localPosition = curPosition;
isDwon = false;
}
}
//拖動結束
if (Input.GetTouch(0).phase == TouchPhase.Ended)
{
isDwon = true;
}
}
}