我有一個彈射物,我想在幾秒鐘后生成并沿游標方向移動它。
基本上,如果我在生成彈丸后不等待,那么移動就會很順利。但由于我在移動彈丸之前等待了幾秒鐘,它實際上是向后移動并擊中了玩家。
這里是代碼。
void crossHairPosition(){
如果(Physics.Raycast(ray, out hit, 100f, layer_Mask))
{
Debug.DrawLine(firePoint.position, hit.point, Color.green)。
destination = hit.point;
crossHairPrefab.transform.position = ray.GetPoint(10);
crossHairPrefab.transform.LookAt(Camera.main.transform)。
}
否則 {
destination = ray.GetPoint(1000);
}
}
void spawnProjectile(){
projectile=Instantiate(projectileObj,player.transform.position,Quaternion.identity);
StartCoroutine(waitforseconds(2))。
}
IEnumerator waitforseconds(float time){
回傳new WaitForSeconds(time)。
moveProjectile()。
}
void moveProjectile(){
Vector3 difference=destination - projectile.transform.position。
float distance=difference.magnitude。
Vector3 direction=difference/distance;
direction.Normalize()。
projectileObj.GetComponent<Rigidbody>().velocity = direction * 10f;
}
uj5u.com熱心網友回復:
為了讓這個問題有一個答案,我把我的評論寫成一個帖子。由于在發射彈丸時延遲計算方向會有問題,但沒有延遲就沒有問題,因此快取方向向量并將其傳遞到IEnumerator中。
代碼可以是這樣的:
IEnumerator waitforseconds(float time)
{
//計算等待前的方向
Vector3 difference=destination - projectile.transform.position。
float distance=difference.magnitude。
Vector3 direction=difference/distance;
direction.Normalize()。
return new WaitForSeconds(time);
//傳入我們預先計算好的方向矢量
moveProjectile(direction)。
}
void moveProjectile(Vector3 direction)
{
projectileObj.GetComponent<Rigidbody>().velocity = direction * 10f;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/332965.html
標籤:
