I’ve been trying to work out how setup a system allowing for projectiles to be shot in multiple directions from the same prefabbed object for my extended version of Laser Defender. Below is what I’ve come up with. Can anyone provide feedback on this?
I’d really appreciate a sanity before I break my game… again
Current System
Weapon prefabs consist of parent GameObject with WeaponConfig.cs containing speed and firing period. Parent GameObject has childed GameObjects containing the projectiles. This is the WeaponConfig.cs script.
public class WeaponConfig : MonoBehaviour {
[SerializeField] float projectileSpeed = 10f;
[SerializeField] float projectileFiringPeriod = 0.5f;
public float GetProjectileSpeed()
{
return projectileSpeed;
}
public float GetProjectileFiringPeriod()
{
return projectileFiringPeriod;
}
}
Weapon prefabs are instantiated via the Player’s FireContinuously method as per below;
private IEnumerator FireContinuously()
{
while(true)
{
GameObject projectile = Instantiate(weapon, transform.position, Quaternion.identity) as GameObject;
projectile.GetComponent<Rigidbody2D>().velocity = new Vector2(0, projectileSpeed);
soundManager.TriggerPlayerShotSFX();
yield return new WaitForSeconds(projectileFiringPeriod);
}
}
Here’s what the prefabs currently look like in the Hierarchy and Inspector.
Potential System Adding Projectile Directions
Add a list to WeaponConfig containg floats representing the X value to be passed to projectile.GetComponent<Rigidbody2D>().velocity = new Vector2(0, projectileSpeed)
E.g.
public class WeaponConfig : MonoBehaviour {
[SerializeField] float projectileSpeed = 10f;
[SerializeField] float projectileFiringPeriod = 0.5f;
[SerializeField] List<float> projectDirectionList; // Populated in inspector
public float GetProjectileSpeed()
{
return projectileSpeed;
}
public float GetProjectileFiringPeriod()
{
return projectileFiringPeriod;
}
public float GetProjectileDirection(float directionListElement)
{
return projectDirectionList[directionListElement];
}
}
private IEnumerator FireContinuously()
{
while(true)
{
GameObject projectile = Instantiate(weapon, transform.position, Quaternion.identity) as GameObject;
projectile.GetComponent<Rigidbody2D>().velocity = new Vector2(0, projectileSpeed);
// Get children of projectile GameObject
List<Rigidbody2D> projectileRigidBodies = projectile.transform.GetComponentsInChildren<Rigidbody2D>();
// Set rBodyCounter for iterating through projectDirectionList
int rBodyCounter = 0;
// For Each child Of projectile
foreach (rBody in projectileRigidBodies)
{
// Apply direction via Velocity
rBody.velocity = new Vector2(projectDirectionList[rBodyCounter], projectileSpeed);
// Iterate rBodyCounter
bBodyCounter++;
}
soundManager.TriggerPlayerShotSFX();
yield return new WaitForSeconds(projectileFiringPeriod);
}
}