C# 使用键移动控件
我正在尝试做一个小游戏,w,a,s,d分别是向前,左,下和右 控件向上、向左、向下和向右移动,但仅移动一次。如果我按两次或三次“W”、“S”、“A”或“D”键,控件只向上移动一次 这是我目前用于移动控制权的代码:C# 使用键移动控件,c#,wpf,keyboard,C#,Wpf,Keyboard,我正在尝试做一个小游戏,w,a,s,d分别是向前,左,下和右 控件向上、向左、向下和向右移动,但仅移动一次。如果我按两次或三次“W”、“S”、“A”或“D”键,控件只向上移动一次 这是我目前用于移动控制权的代码: private void moveRight(Button button) { // Gets the current position of the control Point relativePoint = button.TransformT
private void moveRight(Button button)
{
// Gets the current position of the control
Point relativePoint = button.TransformToAncestor(parentCanvas).Transform(new Point(0, 0));
// Reason for having relative - relative is that its adding onto the previous point.
Canvas.SetLeft(button, relativePoint.X - relativePoint.X + 5);
button.Content = relativePoint;
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.W)
{
moveUp(button1);
}
else if (e.Key == Key.A)
{
moveLeft(button1);
}
else if (e.Key == Key.S)
{
moveDown(button1);
}
else if (e.Key == Key.D)
{
moveRight(button1);
}
}
请帮助或建议我如何着手解决这个问题
我们将非常感谢您的帮助。
谢谢我想明白了,逻辑有点不明白 正确的方法如下:
private void moveRight(Button button)
{
// Gets the current position of the control
Point relativePoint = button.TransformToAncestor(parentCanvas).Transform(new Point(0, 0));
Canvas.SetLeft( button , 5 + relativePoint.X );
button.Content = relativePoint;
}
现在可以用了,谢谢你
Canvas.SetLeft(button, relativePoint.X - relativePoint.X + 5);
使用
希望这会有所帮助 Hi Canvas.SetLeft(按钮,relativePoint.X-relativePoint.X+5);这将始终将“X坐标设置为5”,Y坐标始终为“相对点”的坐标。因此,一旦它第一次设置,那么这些相同的值将被一次又一次地设置。您需要更改在SetLeft方法参数中设置X坐标值的逻辑。您好,谢谢您的评论:)我已经尝试过了,它会添加到以前的X坐标上。例如,坐标是100,按下按钮时,由于某种原因,它会跳到205,这就是我最初尝试第一种方法的原因。嗨,那么问题出在其他地方,因为它对我来说工作正常。
Canvas.SetLeft(button, relativePoint.X + 5);