In the game, there is a situation where oblique movement is achieved by simultaneously pressing two directions to form a diagonal line operation. In Win32GDI development, multiple keys can be obtained by adding the keyboard status in the logical loop. However, the keyboard events in Silverlight are single and cannot be obtained, yuan You raised a question: my Flyer game can only be controlled from the upper left to the lower right, rather than diagonal action. Today we are going to solve this problem and implement the correct action in eight directions.
For the initial idea of this solution, for keyboard input, you can use a queue to save the keyboard status, such as using a List to save the Key status, then, release unused keys during KeyUp, and judge that the Key may be in all directions in the pressed order. However, there are several problems that duplicate keys may occur when multiple keys are pressed, however, if the order of the push is not accurate, the output queue may not be accurate. For example, if I can press ABC at the same time and the order of release is BCA, the result is not an accurate List, this method seems feasible, but it is not necessarily the case in the actual process, so the problem is not solved.
There may be many solutions for this implementation. Here we use an intuitive solution to solve this problem. Using a status table, we can analyze the commonalities of a key-press behavior and Action-direction behavior, they are a 3x3 image:
From the above figure, we can see that it is a 3x3 two-dimensional array. Let's take a look at what it looks like-game controllers. We can use a two-dimensional array to save all States, combine the following numbers to obtain the corresponding status.
As shown in, we can use a state to complete it. The code is written as follows:
Public enum emUserDir
{
Top, bottom, left, right, top left, top right, bottom left, bottom right, middle
}
EmUserDir [,] UserDir = new emUserDir [3, 3]
{
{EmUserDir. Upper left, upper emUserDir., upper right },
{EmUserDir. Left, emUserDir., emUserDir. Right },
{EmUserDir. Bottom left, emUserDir. Bottom, emUserDir. Bottom right}
};
The following example shows the KeyDown event in the MainPage of the self-built project:
Void MainPage_KeyDown (object sender, KeyEventArgs e)
{
String temp = e. Key. ToString ();
Switch (e. Key)
{
Case Key. Up:
If (vertical> 0)
Vertical-= 1;
Break;
Case Key. Down:
If (vertical <2)
Vertical + = 1;
Break;
Case Key. Left:
If (horizontal> 0)
Horizontal-= 1;
Break;
Case Key. Right:
If (horizontal <2)
Horizontal + = 1;
TbTextRightKey. Text = temp + "= Press ";
Break;
}
String Text = UserDir [vertical, horizontal]. ToString ();
}
You can obtain accurate location enumeration information in the final Text. For more intuitive information, let's make an output. Please download the source Code for the specific Code: Download it here.
The final result is as follows. You can download the code and run it directly.