Last active
January 8, 2022 20:23
-
-
Save kurtdekker/a316a952e6228b7be18ad92efc97d5d9 to your computer and use it in GitHub Desktop.
Detect both edge-trigger (pressed) keys and held-to-repeat keys in Unity3D
This file contains 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.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
// @kurtdekker | |
// | |
// cheap and cheerful repeating keys in Unity3D | |
// | |
// You can lift/release them as fast as you like | |
// and exceed the repeat rate. Or just hold it. | |
public class RepeatingKeyDetector : MonoBehaviour | |
{ | |
// how fast do we repeat? | |
public float RepeatInterval; | |
// what keys do we act on? | |
public KeyCode LeftArrow; | |
public KeyCode RightArrow; | |
float leftHeldTimer; | |
float rightHeldTimer; | |
void Reset() | |
{ | |
RepeatInterval = 0.50f; | |
LeftArrow = KeyCode.LeftArrow; | |
RightArrow = KeyCode.RightArrow; | |
} | |
void Update () | |
{ | |
bool goLeftIntent = false; | |
bool goRightIntent = false; | |
// edge-triggered | |
if (Input.GetKeyDown( LeftArrow)) goLeftIntent = true; | |
if (Input.GetKeyDown( RightArrow)) goLeftIntent = true; | |
// repeat-triggered | |
if (Input.GetKey( LeftArrow)) | |
{ | |
leftHeldTimer += Time.deltaTime; | |
if (leftHeldTimer > RepeatInterval) | |
{ | |
goLeftIntent = true; | |
leftHeldTimer -= RepeatInterval; | |
} | |
} | |
else | |
{ | |
leftHeldTimer = 0.0f; | |
} | |
if (Input.GetKey( RightArrow)) | |
{ | |
rightHeldTimer += Time.deltaTime; | |
if (rightHeldTimer > RepeatInterval) | |
{ | |
goRightIntent = true; | |
rightHeldTimer -= RepeatInterval; | |
} | |
} | |
else | |
{ | |
rightHeldTimer = 0.0f; | |
} | |
// TODO: now act on the contents of goLeftIntent and goRightIntent | |
if (goLeftIntent) | |
{ | |
Debug.Log( "Go left - " + Time.time); | |
} | |
if (goRightIntent) | |
{ | |
Debug.Log( "Go right - " + Time.time); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment