Skip to content

Instantly share code, notes, and snippets.

@Protonz
Last active December 23, 2017 16:42
Show Gist options
  • Save Protonz/ae27bcfa4486dc06f6a85bf7c134c0e6 to your computer and use it in GitHub Desktop.
Save Protonz/ae27bcfa4486dc06f6a85bf7c134c0e6 to your computer and use it in GitHub Desktop.
using UnityEngine;
using UniRx;
using System;
using System.Linq;
public class DamageVolumePlayer : MonoBehaviour {
// Health should live in a different component. Just here for simplicity
public FloatReactiveProperty Health = new FloatReactiveProperty(100);
public float DamagePerSecond = 1.0f;
public BoolReactiveProperty InDamageVolume = new BoolReactiveProperty(false);
public BoolReactiveProperty InDamageNegateVolume = new BoolReactiveProperty(false);
public BoolReactiveProperty ShouldTakeDamage = new BoolReactiveProperty(false);
// The Damage Volumes will add/remove themselves from this collection
public ReactiveCollection<DamageVolume> CurrentDamageVolumes = new ReactiveCollection<DamageVolume>();
void Start () {
// Check if in a damage volume
CurrentDamageVolumes.ObserveCountChanged()
.Select(_ => CurrentDamageVolumes.Where(v => v.IsNegateVolume == false).Count())
.Select(count => count > 0)
.DistinctUntilChanged()
.Subscribe(inDamageVolume =>
InDamageVolume.Value = inDamageVolume
).AddTo(this);
// Check if in a damage negate volume
CurrentDamageVolumes.ObserveCountChanged()
.Select(_ => CurrentDamageVolumes.Where(v => v.IsNegateVolume == true).Count())
.Select(count => count > 0)
.DistinctUntilChanged()
.Subscribe(inDamageNegateVolume =>
InDamageNegateVolume.Value = inDamageNegateVolume
).AddTo(this);
// Check if the player should take damage
Observable.CombineLatest(InDamageVolume, InDamageNegateVolume,
( inDamageVolume, inDamageNegateVolume ) => inDamageVolume == true && inDamageNegateVolume == false)
.DistinctUntilChanged()
.Subscribe(shouldTakeDamage =>
ShouldTakeDamage.Value = shouldTakeDamage
).AddTo(this);
// Remove Health if the player should take damage every second
Observable.Interval(TimeSpan.FromSeconds(1))
.Where(_ => ShouldTakeDamage.Value == true)
.Subscribe(_ =>
Health.Value -= DamagePerSecond
).AddTo(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment