用键移动控件

时间:2012-05-28 08:04:36

标签: 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.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);
        }
    }

请帮助或建议我如何解决这个问题。

非常感谢所有帮助。 感谢

2 个答案:

答案 0 :(得分:1)

想出来,逻辑有点过了。

正确的方法是这样的:

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;

     }

现在正在工作,谢谢

答案 1 :(得分:0)

而不是

Canvas.SetLeft(button, relativePoint.X - relativePoint.X + 5); 

使用

Canvas.SetLeft(button, relativePoint.X + 5);

希望这会有所帮助。