2014-10-30 127 views
1

您好,感謝您閱讀本文。檢測「玩家」是屏幕中間的左側還是右側

我對團結相當陌生,但不管這個事實,我做了一個小遊戲,和馬里奧和其他人一樣。一場比賽是你左右移動並跳躍以躲避敵人。

但是我面對一個小小的代碼問題,我似乎無法找到答案來幫助我解決它。

我需要檢測玩家是在屏幕中間的左邊還是右邊,所以我知道相機是否必須向左或向右移動。

這是我迄今爲止創建的相機腳本。

using UnityEngine; 
using System.Collections; 

public class CameraFunction : MonoBehaviour { 

float ydir = 0f; 
public GameObject player; 
//for our GUIText object and our score 
public GUIElement gui; 
float playerScore = 0; 

//this function updates our guitext object 
void OnGUI(){ 
    gui.guiText.text = "Score: " + ((int)(playerScore * 10)).ToString(); 
} 
//this is generic function we can call to increase the score by an amount 
public void increaseScore(int amount){ 
    playerScore += amount; 
} 
//Camera will be disabled when we load a level, set the score in playerprefs 
void OnDisable(){ 
    PlayerPrefs.SetInt ("Score",(int)(playerScore)); 
} 

// Update is called once per frame 
void Update() { 
    //check that player exists and then proceed. otherwise we get an error when player dies 
    if (player) { 


     if (player.transform.position.x > -1) { 

      //update our score every tick of the clock 
      playerScore += Time.deltaTime; 

      transform.position = new Vector3 (transform.position.x + 0.03f, transform.position.y, -10); 
     } 
    } 
} 
} 

我的腳本只檢測「播放器」是否通過當前視圖的中間位置,然後開始移動。

我希望你明白我的意思,並且能夠幫助我。

更新:

如果你看它這樣,我們就可以在2分割畫面,左側和右側部分,ofcourse我們有那些2.

人之間的中間/玩家從屏幕左側開始,必須在地圖上向右移動到最終目標。

現在,當人通過屏幕的中間和右側時,相機將開始向右移動。但我無法檢測到用戶/播放器是否向後移動,然後相機必須「凍結」。

所以如果玩家位置大於屏幕的50%(右側)=相機向右移動。 如果玩家位置是<屏幕的50%(左側)=相機「凍結」。

+0

感謝您的回覆。我做了一些更新,希望能夠更好地解釋它。 – 2014-10-30 08:35:23

回答

2

您可以連接到相機的腳本組件使用:

if(camera.WorldToScreenPoint(player.transform.position).x > Screen.width/2){ 
     Debug.Log("Player is right of the middle of the screen."); 
    } 

在其WorldToScreenPoint被轉換世界座標到屏幕座標。

+0

你知道,你可能只需要看看玩家是否在相機的左側或右側,因爲如果我的記憶能正常工作,相機的「位置」由中心點表示。 – Wade 2015-05-28 22:55:05

+0

這是真的,如果相機總是指向一個軸。這個問題沒有提到它是2D還是3D遊戲。所以如果相機可以旋轉,那麼你需要計算一些向量數學(就像我的答案)。 – maZZZu 2015-05-29 04:43:21

相關問題