Skip to content

Instantly share code, notes, and snippets.

@arturaz
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arturaz/9757939 to your computer and use it in GitHub Desktop.
Save arturaz/9757939 to your computer and use it in GitHub Desktop.
Example of keyboard dashing behaviour for Unity3D using TLPLib Reactive Extensions (https://github.com/tinylabproductions/tlplib)
using System;
using System.Collections;
using com.tinylabproductions.TLPLib.Collection;
using com.tinylabproductions.TLPLib.Functional;
using com.tinylabproductions.TLPLib.Reactive;
using UnityEngine;
namespace Keyboard {
class KeyboardDash : MonoBehaviour {
private const int presses = 2;
public float magnitude, dragCoeficient, timeframeSec, cooldownSec;
public Space movementSpace = Space.World;
internal void Start() {
var up =
doublePress(KeyCode.W).join(doublePress(KeyCode.UpArrow)).
map(_ => new Vector3(0, magnitude));
var down =
doublePress(KeyCode.S).join(doublePress(KeyCode.DownArrow)).
map(_ => new Vector3(0, -magnitude));
var left =
doublePress(KeyCode.A).join(doublePress(KeyCode.LeftArrow)).
map(_ => new Vector3(-magnitude, 0));
var right =
doublePress(KeyCode.D).join(doublePress(KeyCode.RightArrow)).
map(_ => new Vector3(magnitude, 0));
var dashObs = up.join(down).join(left).join(right).onceEvery(cooldownSec);
dashObs.subscribe(v => StartCoroutine(dash(v)));
}
private IEnumerator dash(Vector3 direction) {
while (direction.magnitude > 0.0001) {
transform.Translate(direction * Time.deltaTime, movementSpace);
direction *= dragCoeficient;
yield return null;
}
}
private IObservable<ILinkedList<Tpl<Unit, float>>>
doublePress(KeyCode key) {
return Observable.everyFrame.filter(_ => Input.GetKeyDown(key)).
withinTimeframe(presses, timeframeSec);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment