如何让我的 sprite 对象离开屏幕到左边并出现在右边?

How to make my sprite object go offscreen to the left and have it appear on the right?

Unity 中,我试图让我的 sprite 离开屏幕到左侧并让它出现在屏幕右侧,反之亦然。顺便说一句,我的精灵不断向左或向右移动(取决于用户输入)以进行游戏。

我考虑到精灵需要完全离开屏幕才能出现在右侧。

这是我当前的代码:

void Start () 
{
    minXValueWorld = Camera.main.ScreenToWorldPoint(new Vector3(0,0,0)).x;
    maxXValueWorld = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0, 0)).x;

    playerSize = this.GetComponent<Renderer>().bounds.size;
}

void Move()
{
    if (inputLeft)
    {
        this.transform.position -= new Vector3(speed * Time.deltaTime, 0, 0);
    }
    else
    {
        this.transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
    }
}

void OffscreenCheck()
{

    Vector3 screenPos = Camera.main.WorldToScreenPoint(this.transform.position);
    Vector3 maxWorldXWithPlayerSize = Camera.main.WorldToScreenPoint(new Vector3(maxXValueWorld,0,0) + playerSize/2);
    Vector3 minWorldWithPlayerSize = Camera.main.WorldToScreenPoint(new Vector3(minXValueWorld,0,0) - playerSize/2);

    if (screenPos.x < minWorldWithPlayerSize.x)
    {
        this.transform.position = new Vector3(maxWorldXWithPlayerSize.x, this.transform.position.y, this.transform.position.z);
    }

    if (screenPos.x > maxWorldXWithPlayerSize.x)
    {
        this.transform.position = new Vector3(minWorldWithPlayerSize.x, this.transform.position.y, this.transform.position.z);
    }

}

然后在Update函数中依次调用MoveOffscreenCheck

此代码的问题在于,一旦我的精灵在左侧完全离开屏幕,它就会出现在屏幕右侧,但它不再向左移动。

相反,它只是传送到屏幕外的左侧或右侧位置。因此,我再也看不到它在屏幕上向左或向右移动了。

我很确定我的代码逻辑刚刚好。有谁知道如何解决这个问题?

谢谢

我认为以下应该可行:

void OffscreenCheck()
{

    Vector3 screenPos = Camera.main.WorldToScreenPoint(this.transform.position);
    Vector3 maxWorldWithPlayerSize = new Vector3(maxXValueWorld + playerSize/2,0,0);
    Vector3 minWorldWithPlayerSize = new Vector3(minXValueWorld - playerSize/2,0,0);
    Vector3 maxScreenWithPlayerSize = Camera.main.WorldToScreenPoint(maxWorldWithPlayerSize);
    Vector3 minScreenWithPlayerSize = Camera.main.WorldToScreenPoint(minWorldWithPlayerSize);

    if (screenPos.x < minScreenWithPlayerSize.x)
    {
        this.transform.position = new Vector3(
            maxWorldWithPlayerSize.x,
            this.transform.position.y,
            this.transform.position.z);
    }

    if (screenPos.x > maxScreenWithPlayerSize.x)
    {
        this.transform.position = new Vector3(
            minWorldWithPlayerSize.x,
            this.transform.position.y,
            this.transform.position.z);
    }

}

以上很好地说明了为什么要注意变量的命名方式。当我第一次看你的代码时,我没有把一个事实联系起来,即虽然变量中有 "World" 这个词,但它们实际上是在屏幕坐标中。所以我没有注意到位置分配错误,其中您使用屏幕坐标在 world 坐标中分配 X 坐标。

在上面,我将世界和屏幕坐标向量分离到单独的局部变量中。屏幕坐标用于屏幕外比较本身,而世界坐标用于将精灵实际移动到您想要的位置。

同样,由于缺少完整的代码示例,我无法实际测试以上内容并验证它是否解决了您的问题。不过我觉得会的。