Skip to content

Instantly share code, notes, and snippets.

@CynicatPro
Created July 22, 2021 23:12
Show Gist options
  • Save CynicatPro/f07f97cc0855cfcb684c0d677c3e21c1 to your computer and use it in GitHub Desktop.
Save CynicatPro/f07f97cc0855cfcb684c0d677c3e21c1 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using UnityEngine;
public static class Utilities {
// shifts all array elements to the right, inserting newValue at the beginning
public static void ShiftInto<T>(T[] array, T newValue) {
T carry = newValue;
for (int i=0; i<array.Length; i++) {
// this is basically swapping carry and the array index
T current = array[i];
array[i] = carry;
carry = current;
}
}
}
// Input is a stream of values from some source device
public class InputStream<T> {
const int sampleCount = 64;
public T[] values = new T[sampleCount];
public double[] times = new double[sampleCount];
// Some useful properties
public T current => values[0];
public T last => values[1];
public double currentTime => times[0];
public double lastTime => times[1];
public void Next(T value, double time) {
Utilities.ShiftInto(values, value);
Utilities.ShiftInto(times, time);
}
}
public static class InputStreamExtensions {
public static bool IsIdle (this InputStream<bool> input) => !input.current && !input.last;
public static bool IsPressed (this InputStream<bool> input) => input.current && !input.last;
public static bool IsHeld (this InputStream<bool> input) => input.current && input.last;
public static bool IsReleased(this InputStream<bool> input) => !input.current && input.last;
public static Vector3 Average(this InputStream<Vector3> input, int samples) {
Vector3 total = new Vector3(0f, 0f, 0f);
int count = Mathf.Min(samples, input.values.Length);
for (int i=0; i<count; i++)
total += input.values[i];
return total / count;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputStreamTesting : MonoBehaviour {
static InputStream<bool> jump = new InputStream<bool>();
static InputStream<bool> pickup = new InputStream<bool>();
static InputStream<Vector3> position = new InputStream<Vector3>();
void Update() {
// how you add input to these, do this when you poll the backend API's
jump.Next(Input.GetKey(KeyCode.Space), Time.time);
pickup.Next(Input.GetKey(KeyCode.F), Time.time);
position.Next(transform.position, Time.time);
// when you want to poll input:
if (jump.IsPressed()) print("Jump!");
if (pickup.IsPressed()) print("Pickup!");
}
void OnDrawGizmos() {
// you can poll the data anywhere basically
Gizmos.DrawWireSphere(position.Average(16), 0.1f);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment