我想在玩家与其碰撞后立即在新位置重生对象。 现在我的代码只是在重生时间后生成对象并销毁前一个对象。 我在 unity2d 上的空对象上的代码是
public GameObject point;
private Vector2 screenBounds;
public float respawnTime = 10f;
GameObject star;
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
spawnStar();
StartCoroutine(starWave());
}
public void spawnStar()
{
Debug.Log("Yeah it works");
star = Instantiate(point) as GameObject;
star.transform.position = new Vector2(Random.Range(-screenBounds.x, screenBounds.x), Random.Range(-screenBounds.y, screenBounds.y));
}
IEnumerator starWave()
{
while (true)
{
yield return new WaitForSeconds(respawnTime);
Destroy(star);
spawnStar();
}
}
对象预制上的脚本是
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Player")
{
Debug.Log("this is star collider destory");
Destroy(this.gameObject);
}
}
答案 0 :(得分:0)
Spawner 脚本
public GameObject point;
void Start()
{
spawnStar();
}
public void spawnStar()
{
Debug.Log("Yeah it works");
star = Instantiate(point) as GameObject;
}
预制脚本
// how long before our star moves
private timeBeforeMoving = 10f;
// our current time
private currentTimer = 0.0f;
// the screen size
private Vector2 screenBounds;
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
transform.position = GenerateNewPosition();
}
private void Update()
{
// increase the time that has passed
currentTimer += Time.deltaTime;
// we have reached the timer threshold, so move the star
if(currentTimer >= timeBeforeMoving)
{
MoveOurStar();
}
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Player")
{
MoveOurStar();
}
}
private void MoveOurStar()
{
// reset the timer as we just moved
currentTimer = 0.0f;
transform.position = GenerateNewPosition();
}
private Vector2 GenerateNewPosition()
{
return new Vector2(Random.Range(-screenBounds.x, screenBounds.x), Random.Range(-screenBounds.y, screenBounds.y));;
}
再次运行您的随机位置代码,而不是销毁它。如果您不希望它在与玩家相同的位置生成,您可以使用 circle cast 来确定对象生成的新位置是否仍在玩家的顶部。如果是,就再随机选择一个新位置。
如果您不想在创建星标时将生成代码放在星标脚本中,您可以在星标脚本中设置一个委托回调来回调生成它的脚本,让它知道它需要动了。或者使 spawner 成为 singleton,甚至实现 eventsystem 以在对象被销毁时触发事件,让管理器知道移动该特定对象。
如果您只想使用我提供的示例代码片段并且在实现循环转换时遇到问题,请告诉我,我可以提供另一个代码片段。
编辑:我稍微更改了代码。现在生成器只会生成一颗星星,星星会在碰撞后处理它的移动位置。