2014-10-30 110 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

相关问题