我正在创建一个简单的UWP游戏,可以控制XML生成的椭圆。
我有一个简单的功能,可以处理箭头键并移动椭圆:
void CoreWindow_KeyDown(CoreWindow sender, KeyEventArgs args)
{
// The click event is up.
if (args.VirtualKey == VirtualKey.Up)
{
// Move up.
Canvas.SetTop(player, Canvas.GetTop(player) - 20);
}
// The click event is down.
else if (args.VirtualKey == VirtualKey.Down)
{
// Move down.
Canvas.SetTop(player, Canvas.GetTop(player) + 20);
}
// The click event is right.
else if (args.VirtualKey == VirtualKey.Right)
{
// Move right.
Canvas.SetLeft(player, Canvas.GetLeft(player) + 20);
}
// The click event is left.
else if (args.VirtualKey == VirtualKey.Left)
{
// Move left.
Canvas.SetLeft(player, Canvas.GetLeft(player) - 20);
}
}
问题是椭圆也移出了窗口,即画布。只要椭圆在窗口内,有没有办法只执行上述功能?我已经尝试过这样的代码,但是没有用:
if (Canvas.GetLeft(player) < levelOneImage.ActualWidth ||
Canvas.GetTop(player) < levelOneImage.ActualHeight)
我只是检查椭圆坐标是否超过了图像坐标。
这是椭圆的XAML:
<Ellipse x:Name="player" Fill="SteelBlue" Height="50" Width="50"/>
这里是椭圆为蓝色元素的游戏外观。
答案 0 :(得分:2)
根据您的操作,这应该可行:
if (Canvas.GetLeft(player) >= 20 && args.VirtualKey == VirtualKey.Left)
{
Canvas.SetLeft(player, Canvas.GetLeft(player) - 20);
}
等