【发布时间】:2015-04-13 11:38:34
【问题描述】:
在Unity 中,我试图让我的精灵离开屏幕到左侧并让它出现在右侧的屏幕外,反之亦然。顺便说一下,我的精灵不断向左或向右移动(取决于用户输入)以进行游戏。
我考虑到精灵需要完全离开屏幕才能出现在右侧。
这是我当前的代码:
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函数中依次调用Move和OffscreenCheck。
这段代码的问题是,一旦我的精灵在左边完全离开屏幕,它就会出现在右边的屏幕外,但它不再向左移动了。
相反,它只是传送到屏幕外的左侧或右侧位置。因此,我不再看到它在屏幕上左右移动。
我很确定我的代码逻辑刚刚关闭。有谁知道如何解决这个问题?
谢谢
【问题讨论】:
-
如果没有a good, minimal, complete code example 清楚地显示行为,很难确定问题可能是什么。但是,您的代码中的一件事对我来说看起来很可疑:
new Vector3(maxXValueWorld,0,0) + playerSize/2。我认为new Vector3(maxXValueWorld + playerSize/2,0,0)会更有意义。按照你的方式,我可以想象在转换到屏幕坐标时会发生一些奇怪的事情,其中x的值不会出现在你认为应该的位置。 -
感谢您的回复。我已根据您的建议修复了我的代码,但我的对象的行为保持不变。基本上发生的情况是,当对象离开屏幕时,对象的 x 位置变为
-19和424(至少基于我的屏幕纵横比)。它只是在那些 x 位置之间切换,这是问题所在,因为这些位置已经是屏幕外的位置。我不确定,但我认为问题在于我的if语句中的逻辑。 -
在我的
if块中,当我将maxWorldXWithPlayerSize.x更改为简单的maxXValueWorld,并将minWorldWithPlayerSize.x更改为minXValueWorld时,对象成功出现在屏幕的另一侧。但我想要的是让它从屏幕外出现,这样对象就不会突然出现,它的一半显示(因为精灵的轴心点在中心)