C# 如何更正当前将精灵完全移出屏幕的代码?
我目前正试图在Unity中为我的游戏对象/精灵编写脚本,使其完全脱离屏幕,然后被销毁。但就我目前的代码而言,精灵并没有完全移出屏幕 以下是我当前的代码:C# 如何更正当前将精灵完全移出屏幕的代码?,c#,unity3d,unity3d-2dtools,C#,Unity3d,Unity3d 2dtools,我目前正试图在Unity中为我的游戏对象/精灵编写脚本,使其完全脱离屏幕,然后被销毁。但就我目前的代码而言,精灵并没有完全移出屏幕 以下是我当前的代码: void MoveObstacle() { this.transform.position -= new Vector3(this.transform.position.x, speed * Time.deltaTime, this.transform.position.z); } void CheckIfOffscreen() {
void MoveObstacle()
{
this.transform.position -= new Vector3(this.transform.position.x, speed * Time.deltaTime, this.transform.position.z);
}
void CheckIfOffscreen()
{
Vector3 spriteSize = this.GetComponentInChildren<Renderer>().bounds.size;
Debug.Log(spriteSize);
Vector3 screenPos = Camera.main.WorldToScreenPoint(this.transform.position);
if(screenPos.y < 0 - spriteSize.y/2)
{
this.DestroyObstacle();
}
}
void DestroyObstacle()
{
Destroy(gameObject);
}
这段代码的问题是,在精灵被破坏之前,它不会使我的精灵完全移出屏幕。当一半的精灵离开屏幕时,它就会消失,这不是我想要的行为
我知道我只是遗漏了一些东西,或者使用了不正确的精灵。有人知道如何解决这个问题吗
谢谢首先,我相信这句话:
this.transform.position -= new Vector3(this.transform.position.x, speed * Time.deltaTime, this.transform.position.z);
应该是:
this.transform.position -= new Vector3(0, speed * Time.deltaTime, 0);
要解决您的问题,请尝试以下方法:
Vector3 screenPos = Camera.main.WorldToScreenPoint(this.transform.position + spriteSize);
if(screenPos.y < 0)
{
this.DestroyObstacle();
}
SpisteSig.y/2在精灵的中间是砰的,所以也许只是SpisteSigy。y不除以2。谢谢评论,但我也尝试过。它仍然消失了一半。我想我可能在屏幕坐标中使用了bounds.size不正确,我想GetComponentChildren应该只是GetComponent。但我还是会把除以2的数去掉。谢谢,我现在可以用了。它现在完全移出屏幕,感谢您指出我在transform.position行上的错误。