Home > Net >  Spawn an object and move it after some seconds along the cursor point in Unity 3D
Spawn an object and move it after some seconds along the cursor point in Unity 3D

Time:09-22

I am having a projectile object which I want to spawn and move it along the cursor direction after some seconds.

Basically if I don't wait after spawning the projectile, then the movement is working great. But since I am waiting for some seconds before I move the projectile, It actually travels backward and hitting the player.

here is the code.

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;
}

CodePudding user response:

Just so the question has an answer, I'll write my comment out as a post. As there is an issue with delaying the direction calculation when firing the projectile, but no issue without a delay, cache the direction vector and pass it into the IEnumerator.

The code could look something like:

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;
}
  • Related