我有一个抛射对象,我想在几秒钟后沿着光标方向产生并移动它。
基本上,如果我不等待产卵后的弹丸,那么运动是伟大的工作。但是因为我在移动投射物之前等待了几秒钟,所以它实际上是向后移动并击中玩家。
代码如下:
void crossHairPosition(){
if (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);
}
else {
destination = ray.GetPoint(1000);
}
}
void spawnProjectile(){
projectile=Instantiate(projectileObj,player.transform.position,Quaternion.identity);
StartCoroutine(waitforseconds(2));
}
IEnumerator waitforseconds(float time){
yield return 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;
}
为了让这个问题有一个答案,我将把我的评论作为一篇文章写出来。由于在发射炮弹时存在延迟方向计算的问题,但没有延迟就没有问题,因此缓存方向矢量并将其传递给IEnumerator。
代码可以是这样的:
IEnumerator waitforseconds(float time)
{
// calculate the direction before the wait
Vector3 difference=destination - projectile.transform.position;
float distance=difference.magnitude;
Vector3 direction=difference/distance;
direction.Normalize();
yield return new WaitForSeconds(time);
// pass in our pre-calculated direction vector
moveProjectile(direction);
}
void moveProjectile(Vector3 direction)
{
projectileObj.GetComponent<Rigidbody>().velocity = direction * 10f;
}