1
votes

I am creating a simple UWP game where I control an XML generated ellipse.

I have a simple function which handles the arrow keys and moves the ellipse:

    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);
            }           
    }

The problem with this is that the ellipse also moves out of the window, i.e. the canvas. Is there a way to only execute above function as long as the ellipse is within the window? I have tried code like this but it did not work:

   if (Canvas.GetLeft(player) < levelOneImage.ActualWidth ||
    Canvas.GetTop(player) < levelOneImage.ActualHeight)

I just check if the ellipse coordinates exeeds the image coordinates.

This is the XAML for the ellipse:

 <Ellipse x:Name="player" Fill="SteelBlue" Height="50" Width="50"/>

Here is how the game looks where the ellipse is the blue element.

Game

1

1 Answers

2
votes

According to what you do, this should work:

   if (Canvas.GetLeft(player) >= 20 && args.VirtualKey == VirtualKey.Left)
   {
     Canvas.SetLeft(player, Canvas.GetLeft(player) - 20);
   }

etc.