Last active
August 29, 2015 13:57
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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