Question by
jintimus · Mar 25, 2021 at 08:03 AM ·
keycodekeyboard input
Swapping KeyCode that will reflect on screen
I have 26 letters that are mapped by using KeyCode on screen, and when I press 'B' on my keyboard, then the letter B will light up on my screen.
This is what I want to do:
I want to swap physical key location, so "A" and "D" will switch places on screen.
Then, when I press the actual keyboard "D", I want the registered input to be A and A will highlight.
Finally, gradually increase numbers of keys that are being swapped.
So far, I got 1 and 3 with this code.
public class Shuffle : MonoBehaviour
public float letterMoveTime = 1f;
public List<GameObject> keys;
IEnumerator shuffleCoroutine;
Typer progressCounter;
private void Awake()
{
keys = new List<GameObject>();
keys.AddRange(GameObject.FindGameObjectsWithTag("EditorOnly"));
// each gameobject keys have this tag.
shuffleCoroutine = null;
progressCounter = GameObject.FindGameObjectWithTag("Finish").GetComponent<Typer>();
}
private void Update()
{
progressCounter = GameObject.FindGameObjectWithTag("Finish").GetComponent<Typer>();
}
public void StartShuffle() // call this on button click
{
if (shuffleCoroutine != null) return;
shuffleCoroutine = DoShuffle();
StartCoroutine(shuffleCoroutine);
}
IEnumerator DoShuffle()
{
List<Vector2> startPos = new List<Vector2>();
List<Vector2> endPos = new List<Vector2>();
//List<KeyCode> startKeyCode = new List<KeyCode>(); this does not work.
//List<KeyCode> endKeyCode = new List<KeyCode>(); this does not work.
foreach (GameObject letter in keys)
{
startPos.Add(letter.transform.position);
endPos.Add(letter.transform.position);
//startKeyCode.Add(letter.GetComponent<KeyCode>()); this does not work.
//endKeyCode.Add(letter.GetComponent<KeyCode>()); this does not work.
}
// shuffle endPos
for (int i = 0; i < Mathf.Ceil(progressCounter.progressCounter/5); i++)
{
Vector2 temp = endPos[i];
int swapIndex = Random.Range(i, endPos.Count);
endPos[i] = endPos[swapIndex];
endPos[swapIndex] = temp;
//KeyCode tempKey = endKeyCode[i];
//endKeyCode[i] = endKeyCode[swapIndex];
//endKeyCode[swapIndex] = tempKey;
}
float elapsedTime = 0f;
while (elapsedTime < letterMoveTime)
{
// wait for next frame
yield return null;
// move each letter
elapsedTime = Mathf.Min(letterMoveTime, elapsedTime + Time.deltaTime);
float t = elapsedTime / letterMoveTime;
for (int i = 0; i < startPos.Count; i++)
{
keys[i].transform.position = Vector2.Lerp(startPos[i], endPos[i], t);
//startKeyCode[i] = endKeyCode[i];
}
}
// allow shuffling to occur again
shuffleCoroutine = null;
}
Does anyone have a good way to do this?
Comment