我有一個GameObject
,它是在Unity 2D模式下在屏幕上創建的。遊戲對象上的GUI元素的本地和世界座標
GameObject
的座標是(3, 3)
。在連接到GameObject
劇本,我有以下OnGUI()
方法:
void OnGUI() {
if(GUI.Button(new Rect(renderer.bounds.min.x, renderer.bounds.min.y, renderer.bounds.max.x, renderer.bounds.max.y), "")) {
Debug.Log ("My Position: " + this.transform.position.x + ", " + this.transform.position.y);
}
}
但是當我運行了統一的項目,在屏幕的左上角被創建,而不是正好覆蓋GameObject
的GUI.Button
。原因是因爲地方和世界座標的差異?
如何在遊戲對象上創建一個GUI.Button()
?
更新:閱讀@ 0Andrea的回答後,我更新的代碼。問題仍然存在:
private Vector3 worldPos;
void Start() {
worldPos = Camera.main.WorldToViewportPoint(gameObject.transform.position);
}
void OnGUI() {
if(GUI.Button(new Rect(worldPos.x, worldPos.y, 1, 1), "")) {
Debug.Log ("My Position: " + this.transform.position.x + ", " + this.transform.position.y);
}
}
的GUI.Button
仍定位在屏幕的左上角,而不是通過遊戲對象。我錯過了什麼?
試過。問題依然存在。看到我更新的問題。 – Raptor 2014-10-27 10:24:55