using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ChildExploder : MonoBehaviour {

	public float explodeScale = 1.0f;

	private float timeLeft = 15.0f;

	private bool destroying = false;

	private List<Transform> children = new List<Transform>();

	public void Start() {
		for (int i = 0; i < transform.childCount; ++i) {
			children.Add (transform.GetChild(i));
		}
	}

	public void Update() {
		if (destroying) {
			timeLeft -= Time.deltaTime;
			if (timeLeft <= 0.0f) {
				foreach (Transform child in children) {
					Destroy(child.gameObject);
				}
				Destroy(gameObject);
			}
		}
	}

	public void explode() {
		destroying = true;

		// go over all children, and "unleash" them
		foreach (Transform child in children) {
			child.parent = null;
			Rigidbody body = child.gameObject.GetComponent<Rigidbody>();
			if (!body) {
				body = child.gameObject.AddComponent<Rigidbody>();
			}
			body.velocity = new Vector3(Random.Range (-20, 20) * explodeScale, Random.Range (30, 50) * explodeScale, Random.Range (-20, 20) * explodeScale);
			body.angularVelocity = new Vector3(Random.Range (-0.5f, 0.5f), Random.Range (-0.5f, 0.5f), Random.Range(-0.5f, 0.5f));
			child.gameObject.layer = 0;
		}
	}
}
