步驟
1.實現小地圖
小地圖使用Render Texture是很容易實現的,演示效果如下圖所示:
2.轉換座標
當點擊小地圖時,可以獲得點擊位置的屏幕空間下的座標,如果點擊位置位於小地圖周圍的深色區域,則不予處理,當點擊到小地圖上時,需要將點擊位置轉換到小地圖座標系:
在屏幕空間中左下角爲(0,0),右上角爲(1,1)所以座標變換只需要進行比例變換就行,不過要考慮兩個座標原點之間的偏移,因爲在做的時候用的1920*1080分辨率,所以所有的比例按照這個數值進行計算,只要將圖片錨點設置好後,並且畫布設置爲隨屏幕大小自適應後其他比例也可以使用,這裏我用來存放render texture的Raw Image的寬高都爲1000:
設點擊位置在屏幕空間下爲(s_x,s_y),轉換後在小地圖座標系下爲(m_x,m_y);
則轉換式爲:
3.發出射線
轉換後的座標與實現小地圖Camera的視圖空間相同,此時可以讓小地圖Camera產生射線與場景發生碰撞獲得位置信息.
主要代碼:
public void OnPointerClick(PointerEventData eventData) {
Vector2 tempVector = new Vector2(eventData.pointerCurrentRaycast.screenPosition.x / Screen.width, eventData.pointerCurrentRaycast.screenPosition.y / Screen.height);
Vector2 raypoint=new Vector2((tempVector.x-(460/1920.0f))/(1000/1920.0f),(tempVector.y-(40/1080.0f))/(1000/1080.0f));
Ray ray = Camera.main.ViewportPointToRay(raypoint);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity)) {
//設置玩家移動目標爲點擊地點
player.SetDestination(hit.point);
}
//LineRender指向點擊位置
lineDraw.SetPositions(new Vector3[2] { Vector3.zero, hit.point });
}
將改代碼放於小地圖上即可。