试图在 unity3d 中将游戏对象保持在屏幕左右边界内

trying to keep a game object within the screen left and right bounds in 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);
    }
 }

我正在开发一款带有 orthographic 摄像头的 2D 游戏,我的问题是游戏对象一直在屏幕外,我是不是漏掉了什么?

首先,您的函数从未被调用,因为它的名称中有拼写错误。应该是 Update 而不是 update.

其次,坐标问题是代码混合了屏幕坐标和世界坐标。屏幕坐标从 (0, 0)(Screen.width, Screen.height)。可以使用 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));
    }

经过一些研究,我找到了一个解决方案希望对我很有效:

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