射線檢測(需要碰撞器)
// 創建一條點擊位置為游標位置的射線
Ray rays = Camera.main.ScreenPointToRay(Input.mousePosition);
//將射線以黃色的表示出來
Debug.DrawRay(rays.origin, rays.direction * 100, Color.yellow);
//創建一個RayCast變數用于存盤回傳資訊
RaycastHit hit;
//將創建的射線投射出去并將反饋資訊存盤到hit中
if (Physics.Raycast(rays, out hit))
{
//獲取被射線碰到的物件transfrom變數
target = hit.transform.position;
}
target就是被選中的物體的坐標
螢屏坐標對比(不需要碰撞器)
//設定滑鼠點擊的精度
WHrate = (float)Screen.width / (float)Screen.height;
xdelta = Screen.width * delta / WHrate;
ydelta = Screen.height * delta;
Vector3 screenPos;
Vector3 mousePos;
foreach (Vector3 v3 in positions)
{
//把包圍盒中心點轉化為螢屏坐標
screenPos = Camera.main.WorldToScreenPoint(v3);
mousePos = Input.mousePosition;
//如果滑鼠點擊的位置在包圍盒中心點螢屏坐標的一定范圍內
if (mousePos.x >= screenPos.x - xdelta && mousePos.x <= screenPos.x + xdelta
&& mousePos.y >= screenPos.y - ydelta && mousePos.y <= screenPos.y + ydelta)
{
target = v3;
break;
}
}
包圍盒(不需要碰撞器)
//判斷模型的包圍盒是否與射線互動
if (meshes[i].bounds.IntersectRay(rays))
{
target = meshes[i].bounds.center;
break;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/388015.html
標籤:其他
上一篇:井字棋(棋子可消去(拿走))
