- Home /
Issue With Lists and Keycodes
I'm trying to queue up pressed buttons in a list, for example if you press W, A, D they should be in the list. I got this working but that is not the issue.
List<KeyCode> queuedMovement = new List<KeyCode>(4);
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
queuedMovement.Add(KeyCode.W);
}
if (Input.GetKeyDown(KeyCode.D))
{
queuedMovement.Add(KeyCode.D);
}
if (Input.GetKeyDown(KeyCode.S))
{
queuedMovement.Add(KeyCode.S);
}
if (Input.GetKeyDown(KeyCode.A))
{
queuedMovement.Add(KeyCode.A);
}
}
As you can see this queues up to 4 keys. The game is a simple 2D game and when you press for example "S" you add a downward force to the Player and you can't move until the player has hit something. Instead of checking if the Player has hit something I check the velocity of the Player.
if (rb.velocity.x == 0 && rb.velocity.y == 0 && queuedMovement.Count != 0)
After that I add the force to the corresponding button pressed and remove the pressed key from the list.
if (rb.velocity.x == 0 && rb.velocity.y == 0 && queuedMovement.Count != 0)
{
switch (queuedMovement[0])
{
case KeyCode.W:
rb.AddForce(new Vector3(0, moveForce * 100));
break;
case KeyCode.D:
rb.AddForce(new Vector3(moveForce * 100, 0));
break;
case KeyCode.S:
rb.AddForce(new Vector3(0, -moveForce * 100));
break;
case KeyCode.A:
rb.AddForce(new Vector3(-moveForce * 100, 0));
break;
}
queuedMovement.RemoveAt(0);
}
This all works perfectly but sometimes the player moves diagonal, meaning that 2 forces get added together and it results in that. I've tried to find a work-around this for couple of hours and I can't. I know this sounds very vague but if you need more details about anything I will provide it. Thanks.
Answer by IggyZuk · Apr 03, 2017 at 10:27 PM
Let me just point out that the value you pass to the constructor of a List<T>
is only the initial capacity; it can and will go beyond it if you try to add more values to a list that is at full capacity.
capacity
Type: System.Int32
The number of elements that the new list can initially store.
Code wise — I see nothing wrong. Perhaps the only concerning part is x == 0 && y == 0
. You could instead try RigidBody.IsSleeping.
Hi! I noticed that the List goes beyond 4, is there any way to limit it? I mean without any work-arounds. Also thanks for the Rigidbody2D.IsSleeping, it does work but for some reason it has a delay. I press a button and after 0.2-0.3 seconds it does register. Any idea what the problem is?
Your answer
![](https://koobas.hobune.stream/wayback/20220612114613im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Key not recognized 2 Answers
C# Script Simulating Input.inputString 0 Answers
Last key pressed 1 Answer
A node in a childnode? 1 Answer
Multiple Cars not working 1 Answer