I’d like to make use of the bullet pool spawning system used in Angry Bots which keeps a pool of bullet objects in the scene for instant use. The system uses translation to move the bullets however which isn’t right for the game I’m working on. So I would like to instead make it use Rigidbodies and move the bullets using AddForce().
I’ve tried firing the bullet from various places, in both the Spawnng script and the Destroying but the results seem to vary. For instance, the bullets either speed up as I’m firing, or the system won’t recycle them correctly.
There are 2 brief scripts which are shown below. One Spawns the bullets and the other fires them (using translation) and them destroys them after a specified time. They have been converted to C# from the original JS in AngryBots with only the relevant sections shown.
Any help would be great - Thanks.
SimpleLaser
using UnityEngine;
using System.Collections;
public class SimpleLaser : MonoBehaviour
{
public Vector3 Direction = Vector3.zero;
public float lifeTime = 2f;
private float spawnTime = 0.0f;
public bool destroyForMe = false;
public float ShotForce;
public void OnEnable()
{
Debug.LogWarning("OnEnable");
// The time this object spawned
spawnTime = Time.time;
gameObject.rigidbody.velocity = Vector3.zero;
gameObject.rigidbody.angularVelocity = Vector3.zero;
// This is the force being added.
gameObject.rigidbody.AddForce(Direction * ShotForce);
}
void Update()
{
if (Time.time > spawnTime + lifeTime) // ||dist < 0)
{
Debug.LogWarning("Spawner.Destroy(gameObject)");
Spawner.Destroy(gameObject);
}
}
}
EnemyBehaviour
public IEnumerator DoFireAnim()
{
// Causes the coroutine to repeat
while (true)
{
Enemy_Anim_obj.animation[roll.name].speed = 2;
Enemy_Anim_obj.animation.CrossFade(roll.name, 0.2f);
yield return new WaitForSeconds(RollTime);
Enemy_Anim_obj.animation.Stop(roll.name);
Enemy_Anim_obj.animation[open.name].speed = 2;
Enemy_Anim_obj.animation.CrossFade(open.name, 0.2f);
if (Enemy_Anim_obj.animation.IsPlaying(open.name))
{
// Wait
}
else
Enemy_Anim_objEnemy_Anim_obj.animation.CrossFade(idle.name, 0.2f);
yield return new WaitForSeconds(0.3f);
shootingFlag = true;
Debug.Log("Called Shoot()");
// Enough time to fire bullets
yield return new WaitForSeconds(0.6f);
Enemy_Anim_obj.animation.CrossFade(close.name, 0.2f);
}
}
//--------------------------------------------------------
void FixedUpdate()
{
if (shootingFlag)
{
Debug.LogWarning("SHOOTING");
GameObject newLaserProjectile_L = Spawner.Spawn(LaserProjectile,
Left_gun.position,
Left_gun.rotation) as GameObject;
Vector3 L_GunBulletDir = playerTarget_obj.transform.position - Left_gun.transform.position;
newLaserProjectile_L.transform.rotation = Quaternion.LookRotation(L_GunBulletDir);
newLaserProjectile_L.GetComponent<SimpleLaser>().Direction = L_GunBulletDir;
newLaserProjectile_L.GetComponent<SimpleLaser>().OnEnable();
shootingFlag = false;
}
}