【问题标题】:Detect if "player" is left or right of the middle of screen检测“玩家”是在屏幕中间的左边还是右边
【发布时间】:2014-10-30 17:10:12
【问题描述】:

您好,感谢您阅读本文。

我对 Unity 还很陌生,但不管这个事实,我还是做了一个小游戏,和马里奥等人一样。一个游戏是你左右移动并跳跃以避免敌人。

但是我遇到了一点代码问题,我似乎无法找到答案来帮助我解决它。

我需要检测玩家是在屏幕中间的左边还是右边,所以我知道相机是否必须向左或向右移动。

这是我目前创建的相机脚本。

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);
        }
    }
}
}

我的脚本只检测“玩家”是否通过当前视图的中间然后开始移动。

我希望你明白我的意思,并且能够帮助我。

更新:

如果你这样看,我们可以将屏幕分成左右两部分,当然我们还有这两个之间的中间部分。

人物/玩家从屏幕左侧开始,必须向右移动穿过地图到达最终目标。

现在,当该人经过中间并进入屏幕右侧时,相机将开始向右移动。但我无法检测到用户/玩家是否向后移动,然后他的相机必须“冻结”。

因此,如果玩家位置 > 屏幕的 50%(右侧)= 相机向右移动。 如果玩家位置

【问题讨论】:

  • 感谢您的回复。我做了一些更新,希望能更好地解释它。
  • > This is a generic function... 不,increaseScore 不是通用函数。泛型函数有<> 括号,例如DestroyAllObjects<TObject>

标签: unity3d


【解决方案1】:

您可以在附加到相机的任何脚本组件中使用它:

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

其中WorldToScreenPoint 正在将世界坐标转换为屏幕坐标。

【讨论】:

  • 您知道,您可能只需要查看玩家通常是在相机的左侧还是右侧,因为如果我的记忆正确,相机“位置”由中心点表示。
  • 这是真的,如果相机总是沿着一个轴指向。问题没有提到它是 2D 还是 3D 游戏。所以如果相机可以旋转,那么你需要计算一些向量数学(就像我的回答一样)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多