1
Fork 0
mirror of https://github.com/Steffo99/gravity-fusion.git synced 2024-11-29 03:24:30 +00:00
gravity-fusion/Assets/Components/Merge.cs

66 lines
1.9 KiB
C#
Raw Normal View History

2019-10-05 10:36:09 +00:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CircleCollider2D))]
public class Merge : MonoBehaviour
{
[Header("Config")]
public GameObject mergeIntoPrefab;
2019-10-05 11:06:48 +00:00
public bool setMergedMassFromTotal;
2019-10-05 10:36:09 +00:00
[Header("References")]
protected new CircleCollider2D collider;
[Header("Internals")]
protected List<Merge> mergeables;
private void Start()
{
collider = GetComponent<CircleCollider2D>();
mergeables = new List<Merge>();
mergeables.Add(this);
}
private void OnTriggerEnter2D(Collider2D other) {
Merge otherMerge = other.GetComponent<Merge>();
2019-10-05 11:06:48 +00:00
if(otherMerge != null) {
mergeables.Add(otherMerge);
if(CanMerge()) DoMerge();
}
2019-10-05 10:36:09 +00:00
}
private void OnTriggerExit2D(Collider2D other) {
Merge otherMerge = other.GetComponent<Merge>();
2019-10-05 11:06:48 +00:00
if(otherMerge != null) {
mergeables.Remove(otherMerge);
}
2019-10-05 10:36:09 +00:00
}
protected bool CanMerge() {
2019-10-05 11:06:48 +00:00
return mergeables.Count >= 5;
2019-10-05 10:36:09 +00:00
}
protected void DoMerge() {
GameObject mergeResult = Instantiate(mergeIntoPrefab, transform.position, Quaternion.identity);
MergedInfo mergedInfo = mergeResult.AddComponent<MergedInfo>();
mergedInfo.mergedCount = mergeables.Count;
2019-10-05 11:06:48 +00:00
foreach(Merge merged in mergeables.ToArray()) {
2019-10-05 10:36:09 +00:00
Rigidbody2D mergedBody = merged.GetComponentInParent<Rigidbody2D>();
if(mergedBody != null) {
mergedInfo.mergedMass += mergedBody.mass;
}
2019-10-05 11:06:48 +00:00
Destroy(merged.transform.parent.gameObject);
}
if(setMergedMassFromTotal) {
Rigidbody2D mergeRigidbody = mergeResult.GetComponent<Rigidbody2D>();
if(mergeRigidbody != null) {
mergeRigidbody.useAutoMass = false;
mergeRigidbody.mass = mergedInfo.mergedMass;
}
2019-10-05 10:36:09 +00:00
}
}
}