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/Merger.cs

80 lines
2.1 KiB
C#
Raw Normal View History

2019-10-05 18:41:07 +00:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CircleCollider2D))]
public class Merger : MonoBehaviour
{
2019-10-06 13:04:50 +00:00
public float mergeAfterSeconds;
2019-10-07 15:50:34 +00:00
[HideInInspector]
public bool mergeEnabled;
2019-10-05 18:41:07 +00:00
protected List<Merger> mergeCandidates;
2019-10-07 11:44:26 +00:00
[HideInInspector]
public Particle particle;
2019-10-05 18:41:07 +00:00
protected Collider2D Collider {
get {
return particle.mergeCollider;
}
}
protected int ParticlesToMerge {
get {
return particle.gameController.particlesToMerge;
}
}
protected void Awake() {
particle = GetComponentInParent<Particle>();
2019-10-06 17:04:47 +00:00
mergeCandidates = new List<Merger>();
2019-10-05 18:41:07 +00:00
}
protected void Start() {
2019-10-06 13:04:50 +00:00
mergeEnabled = false;
Invoke("EnableMerge", mergeAfterSeconds);
}
protected void EnableMerge() {
mergeEnabled = true;
if(CanMerge()) DoMerge();
2019-10-05 18:41:07 +00:00
}
2019-10-06 13:04:50 +00:00
protected void OnTriggerEnter2D(Collider2D other) {
2019-10-05 18:41:07 +00:00
Merger otherMerger = other.GetComponent<Merger>();
if(otherMerger == null) return;
Particle otherParticle = otherMerger.particle;
if(this.particle.Tier != otherParticle.Tier) return;
mergeCandidates.Add(otherMerger);
if(CanMerge()) DoMerge();
}
2019-10-06 13:04:50 +00:00
protected void OnTriggerExit2D(Collider2D other) {
2019-10-05 18:41:07 +00:00
Merger otherMerger = other.GetComponent<Merger>();
if(otherMerger == null) return;
mergeCandidates.Remove(otherMerger);
}
protected bool CanMerge() {
2019-10-06 13:04:50 +00:00
int mergeableCount = 0;
foreach(Merger mergeCandidate in mergeCandidates) {
if(mergeCandidate.mergeEnabled) mergeableCount += 1;
}
return mergeEnabled && mergeableCount >= ParticlesToMerge;
2019-10-05 18:41:07 +00:00
}
protected void DoMerge() {
particle.Tier += 1;
foreach(Merger merged in mergeCandidates.ToArray()) {
2019-10-05 21:50:43 +00:00
if(merged == null) continue;
2019-10-05 18:41:07 +00:00
Destroy(merged.particle.gameObject);
}
2019-10-05 21:50:43 +00:00
mergeCandidates.Clear();
particle.mergeCollider.enabled = false;
particle.mergeCollider.enabled = true;
2019-10-05 18:41:07 +00:00
}
}