- Home /
Bullets that shoot on a delay
Hello All,
I am working on a 2dSideScoller and I want one of the enemies to shot in a V pattern but I want one bullet to shot the after .2 seconds right now they both just shoot at the same time, any help would be appreciated I posted my code below
IEnumerator Wait(float seconds){ yield return new WaitForSeconds (seconds); } public void shootBullet() { if (gameObject.name == "FireEnemy2") { isShooting = true; Vector2 playerPosition = GameObject.Find("Player").GetComponent<Transform>().position; Rigidbody2D currentBullet = (Rigidbody2D)Instantiate(bulletPrefab, transform.position, Quaternion.identity); Rigidbody2D currentBullet1 = (Rigidbody2D)Instantiate(bulletPrefab, transform.position, Quaternion.identity); Rigidbody2D currentBullet2 = (Rigidbody2D)Instantiate(bulletPrefab, transform.position, Quaternion.identity); Vector3 destination = GameObject.Find("Player").GetComponent<Transform>().position; Vector3 differencePosition = new Vector3(destination.x - transform.position.x, destination.y - transform.position.y, 0); Vector3 differencePosition1 = new Vector3(destination.x - transform.position.x, destination.y - transform.position.y + 0.9f, 0); Vector3 differencePosition2 = new Vector3(destination.x -transform.position.x, destination.y - transform.position.y - 0.9f, 0); currentBullet.AddForce(differencePosition * bulletForce); StartCoroutine(Wait(.2f)); currentBullet1.AddForce(differencePosition1 * bulletForce); StartCoroutine(Wait(.2f)); currentBullet2.AddForce(differencePosition2 * bulletForce); isShooting = false; }
Answer by Key_Less · Apr 13, 2014 at 12:12 AM
The problem is that your coroutine is essentially doing noting. If you want to delay adding a force to your bullet, you'll need to add your code inside of the coroutine to ensure your bullet isn't fired until after the coroutine has yielded for 0.2 seconds. For example...
private IEnumerator Wait()
{
// Fire first bullet here.
yield return new WaitForSeconds (0.2f); // Wait 0.2 seconds.
// Now that we've yielded for 0.2 seconds, fire the second bullet here.
}
You can read more about how to properly use coroutines in JS and C# here.
Your answer
Follow this Question
Related Questions
Which Camera Rotation is Good While Making 2D Game? 0 Answers
Echolocation in 2D top down game 0 Answers
Inverting Position on One Axis 0 Answers
Unity 2D Multiplayer Spawning 0 Answers
Need trigger collider script. 1 Answer