2015-02-04 49 views
1

權界我有我的遊戲對象的代碼波紋管:試圖保持屏幕內的遊戲對象留在unity3d

private float screenx; 
Vector3 playerPosScreen; 
void Start() { 
screenx=Camera.main.pixelWidth-renderer.bounds.size.x ; 
} 

void update(){ 
    playerPosScreen = Camera.main.WorldToScreenPoint(transform.position); 
    if (playerPosScreen.x >= screenx) { 
     //playerPosScreen.x=screenx; 
     transform.position=new Vector3 (screenx, transform.position.y,transform.position.z); 
    } 
    //txt.text = playerPosScreen.x.ToString(); 
    else if(playerPosScreen.x<=renderer.bounds.size.x){ 
     transform.position=new Vector3 (renderer.bounds.size.x, transform.position.y,transform.position.z); 
    } 
} 

我正在開發一個2D遊戲與orthographic相機,我的問題是gameobject繼續走出屏幕,我在這裏錯過了什麼?

回答

5

經過一番研究,我發現了一個解決方案的願望工作優秀與我:

Vector3 playerPosScreen; 
Vector3 wrld; 
float half_szX; 
float half_szY; 
void Start() { 
    wrld = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0.0f, 0.0f)); 
    half_szX = renderer.bounds.size.x/2; 
    half_szY = renderer.bounds.size.y /2 ; 
} 
void Update() { 
    playerPosScreen = transform.position; 
if (playerPosScreen.x >=(wrld.x-half_szX)) { 
     playerPosScreen.x=wrld.x-half_szX; 
     transform.position=playerPosScreen; 
    } 
    if(playerPosScreen.x<=-(wrld.x-half_szX)){ 
     playerPosScreen.x=-(wrld.x-half_szX); 
     transform.position=playerPosScreen; 
    } 
} 
2

首先你的功能從來不會被調用,因爲它的名字中有拼寫錯誤。它應該是Update而不是update

其次,座標問題是代碼混合了屏幕座標和世界座標。屏幕座標從(0, 0)(Screen.width, Screen.height)。 Z座標可以從世界座標改變爲屏幕座標WorldToScreenPoint,並返回ScreenToWorldPoint,其中Z值是轉換點距相機的距離。

下面是一個完整的代碼示例,它可以改變玩家的位置後使用,以確保它是屏幕區域內:

Vector2 playerPosScreen = Camera.main.WorldToScreenPoint(transform.position); 
    if (playerPosScreen.x > Screen.width) 
    { 
     transform.position = 
      Camera.main.ScreenToWorldPoint(
       new Vector3(Screen.width, 
          playerPosScreen.y, 
          transform.position.z - Camera.main.transform.position.z)); 
    } 
    else if (playerPosScreen.x < 0.0f) 
    { 
     transform.position = 
      Camera.main.ScreenToWorldPoint(
       new Vector3(0.0f, 
          playerPosScreen.y, 
          transform.position.z - Camera.main.transform.position.z)); 
    } 
+0

對於輸入錯誤'update',我感到抱歉,這只是一個輸入錯誤,並且非常感謝您提供關於澄清和代碼的提示。我會測試它:) – Sora

+0

沒問題。至少對我來說,代碼在正交和透視相機上都可以工作。 – maZZZu