我想創建一種太空船遊戲,在這裏你用箭頭鍵控制圖像(顯然是飛船),以便向上/向下/向右移動。 爲此我使用了一個CoreWindow.KeyDown事件。用KeyDown事件在畫布上的光滑元素運動UWP
它實際上工作正常,但運動不夠流暢。 每當我按下其中一個箭頭鍵,圖像然後: 1.向該方向移動一步 2.凍結,爲半秒鐘(甚至更少) 3.然後繼續移動沒有麻煩。 (一個「步驟」,是一個'int'變量,它包含許多像素,比如20)。
當然,這是沒辦法運行一個遊戲。當我按下其中一個沒有「半秒」延遲的方向鍵時,我希望船能夠順利移動。 這是我的代碼:
public sealed partial class MainPage : Page
{
double playerYAxisPosition;
double playerXAxisPosition;
int steps = 20;
bool upMovement;
bool downMovement;
bool rightMovement;
bool leftMovement;
public MainPage()
{
this.InitializeComponent();
Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
Window.Current.CoreWindow.KeyUp += CoreWindow_KeyUp;
}
// Recognizes the KeyDown press and sets the relevant booleans to "true"
private void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args) {
playerYPosition = (double) playerShip.GetValue(Canvas.TopProperty);
playerXPosition = (double) playerShip.GetValue(Canvas.LeftProperty);
if (args.VirtualKey == Windows.System.VirtualKey.Up) {
upMovement = true;
}
else if (args.VirtualKey == Windows.System.VirtualKey.Down) {
downMovement = true;
}
else if (args.VirtualKey == Windows.System.VirtualKey.Left) {
leftMovement = true;
}
else if (args.VirtualKey == Windows.System.VirtualKey.Right) {
rightMovement = true;
}
movePlayer();
}
// recognizes the KeyUp event and sets the relevant booleans to "false"
private void CoreWindow_KeyUp(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args) {
if (args.VirtualKey == Windows.System.VirtualKey.Up) {
upMovement = false;
}
else if (args.VirtualKey == Windows.System.VirtualKey.Down) {
downMovement = false;
}
else if (args.VirtualKey == Windows.System.VirtualKey.Left) {
leftMovement = false;
}
else if (args.VirtualKey == Windows.System.VirtualKey.Right) {
rightMovement = false;
}
}
// Calls the movement Methods of the relevant direction
private void movePlayer() {
if (upMovement) {
moveUp();
}
if (downMovement) {
moveDown();
}
if (rightMovement) {
moveRight();
}
if (leftMovement) {
moveLeft();
}
}
private void moveUp() {
playerShip.SetValue(Canvas.TopProperty, playerYPosition - stepsToMove);
}
private void moveDown() {
playerShip.SetValue(Canvas.TopProperty, playerYPosition + stepsToMove);
}
private void moveRight() {
playerShip.SetValue(Canvas.LeftProperty, playerXPosition + stepsToMove);
}
private void moveLeft() {
playerShip.SetValue(Canvas.LeftProperty, playerXPosition - stepsToMove);
}
順便說一句,我創建了一個將設置爲「真」或「假」,在每一個KeyDown事件,而不是直接使用KeyDown事件的一些專用的布爾值的原因,是因爲該分隔允許元素(船圖像)也沿對角線移動,而使用「args.VirtualKey == Windows.System.VirtualKey.SomeArrowKey」直接不允許它由於某種原因。
感謝您的幫助。
我把谷歌顛倒了這個.. 非常感謝! 問題解決了:) –