0

我正在尝试制作一个 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);
        }
    }

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

所有帮助将不胜感激。谢谢

4

2 回答 2

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;

     }

它现在工作,谢谢

于 2012-05-28T08:54:48.543 回答
0

代替

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

采用

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

希望这会有所帮助。

于 2012-05-28T08:55:37.007 回答