3DTD/Assets/Scripts/Utilities/ProjectileSpawner.cs

67 lines
2.3 KiB
C#

using System.Collections;
using UnityEngine;
[System.Serializable]
public class ProjectilePattern
{
[SerializeField]
public float Arc = 15;
[SerializeField]
public int Amount = 3;
[SerializeField]
public float Speed = 1;
[SerializeField]
public GameObject bulletPrefab;
[SerializeField]
public bool Burst = true;
[SerializeField]
public float BurstDelay = 0.1f;
}
public class ProjectileSpawner : MonoBehaviour
{
[SerializeField] private float delayBetweenBulletSequences = 0.1f;
public void RunBulletSequence(Vector3 origin, Vector3 normal, Vector3 baseDirection, ProjectilePattern[] bulletSequence)
{
StartCoroutine(RunBulletSequenceCourotine(origin, normal, baseDirection, bulletSequence));
}
private IEnumerator RunBulletSequenceCourotine(Vector3 origin, Vector3 normal, Vector3 baseDirection, ProjectilePattern[] bulletSequence)
{
baseDirection.Normalize();
foreach (ProjectilePattern bulletPattern in bulletSequence)
{
float stepSize = bulletPattern.Arc / ((float)bulletPattern.Amount);
for (int i = 0; i < bulletPattern.Amount; i++)
{
float angle = stepSize * i + stepSize / 2f - bulletPattern.Arc / 2f;
Vector3 bulletDir = Quaternion.AngleAxis(angle, normal) * baseDirection;
GameObject projectile = Instantiate(bulletPattern.bulletPrefab, origin, Quaternion.identity);
Debug.DrawRay(origin, bulletDir, Color.magenta, 5f);
projectile.transform.up = bulletDir;
projectile.GetComponent<Rigidbody>().AddForce(bulletDir * bulletPattern.Speed);
projectile.GetComponent<Projectile>().comingFrom = GetComponent<HealthComponent>();
if (bulletPattern.Burst)
yield return new WaitForSeconds(bulletPattern.BurstDelay);
}
yield return new WaitForSeconds(delayBetweenBulletSequences);
}
}
public static Vector2 rotate(Vector2 v, float deg)
{
float delta = deg * (float)Mathf.Deg2Rad;
return new Vector2(
v.x * Mathf.Cos(delta) - v.y * Mathf.Sin(delta),
v.x * Mathf.Sin(delta) + v.y * Mathf.Cos(delta)
);
}
}