BloodAndGore/Assets/Scripts/Effects/Explodable.cs

74 lines
2.9 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Saltosion.OneWeapon {
public class Explodable : MonoBehaviour {
public GameObject[] BodypartPrefabs;
public bool DebugExplode = false;
[Tooltip("This only applies if this GameObject also has the Health component.")]
public bool KillOnZeroHealth = true;
private CameraFX CameraFX;
private PlayerFun PlayerFun;
private Health Health;
private void Start() {
foreach (GameObject Obj in BodypartPrefabs) {
Rigidbody2D Body = Obj.GetComponent<Rigidbody2D>();
if (Body == null) {
Debug.LogError($"'{Obj.name}' is an explodable bodypart, and does not have a Rigidbody2D!\n\n" +
"Therefore it cannot be exploded. Please provide one.\n" +
"Following is the GameObject that needs to get a Rigidbody2D.");
}
}
CameraFX = Camera.main.GetComponent<CameraFX>();
PlayerFun = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerFun>();
Health = GetComponent<Health>();
}
private void Update() {
if (DebugExplode) {
DebugExplode = false;
Explode(false);
}
if (Health != null && Health.CurrentHealth <= 0 && KillOnZeroHealth) {
Explode(true);
}
}
public void Explode(bool destroyGameObject) {
int Count = Mathf.Clamp((int)(BodypartPrefabs.Length * Random.value + 1), 1, BodypartPrefabs.Length);
for (int i = 0; i < Count; i++) {
GameObject Obj = BodypartPrefabs[i];
// No body parts flying in censored mode
float DirectionRadians = Random.value * Mathf.PI * 2.0f;
Vector2 Direction = new Vector2(Mathf.Cos(DirectionRadians), Mathf.Sin(DirectionRadians));
if (!Options.CensorGore) {
GameObject NewObj = Instantiate(Obj, transform.position, new Quaternion(), null);
Rigidbody2D Bodypart = NewObj.GetComponent<Rigidbody2D>();
if (Bodypart == null) {
continue;
}
float Force = 0.5f + Random.value * 0.5f;
Bodypart.AddForce(Direction * Force, ForceMode2D.Impulse);
Bodypart.AddTorque((Random.value - 0.5f) * Force, ForceMode2D.Impulse);
}
// Blood is replaced by flowers though, no problem with that
BloodLauncher.Splatter(transform.position + (Vector3)Direction * 0.5f, Vector2.zero, 70, 50f, 360f);
}
PlayerFun.Explosion(false);
CameraFX.ScreenShake(10);
if (destroyGameObject) {
Destroy(gameObject);
}
}
}
}