我如何让我的玩家和敌人发生碰撞?

How do i make a collision between my player and enemy?

public 密封部分 class MainPage : Page

{

    Enemy[] arr_Enemy = new Enemy[10];

    Rectangle Enemy;

    Rectangle Player;

    Random rnd = new Random();     

    public MainPage()           

    {

    this.InitializeComponent();

    Window.Current.CoreWindow.KeyDown += PlayerMovement;

    MyCanvas.Background = new ImageBrush

       {

ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/Background.jpg"))

        };

       Player = new Rectangle();

       Player.Width = 50;

       Player.Height = 50;

       Player.Fill = new ImageBrush

        {

ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/PlAYER2.GIF")) };

       MyCanvas.Children.Add(Player);

       Canvas.SetTop(Player, 700);

       Canvas.SetLeft(Player, 900);

        for (int i = 0; i < arr_Enemy.Length; i++)
        {
            Enemy = new Rectangle();
            Enemy.Fill = new ImageBrush
            {

ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/enemy.GIF")) };

         Enemy.Width = 120;

         Enemy.Height = 115;

         MyCanvas.Children.Add(Enemy);

         Canvas.SetTop(Enemy, rnd.Next(750));

         Canvas.SetLeft(Enemy, rnd.Next(750));
        }

    }
    private void PlayerMovement(CoreWindow sender, KeyEventArgs args)
    {


  VirtualKey movement = args.VirtualKey;

    switch (movement)

       {

         case VirtualKey.Up:

             Canvas.SetTop(Player, Canvas.GetTop(Player) - 10);

         break;

         case VirtualKey.Down:

             Canvas.SetTop(Player, Canvas.GetTop(Player) + 10);

         break;

         case VirtualKey.Left:

             Canvas.SetLeft(Player, Canvas.GetLeft(Player) - 10);

         break;

         case VirtualKey.Right:

             Canvas.SetLeft(Player, Canvas.GetLeft(Player) + 10);

         break;

        }
        

(我尝试过这样的 if 语句,但没有成功。)-

if (Canvas.GetLeft(玩家) == Canvas.GetLeft(敌人) &&

Canvas.GetTop(玩家)== Canvas.GetTop(敌人))

How do i make a collision between my player and enemy?

可以使用Intersect方法判断元素是否有共同点。例如

private Rect DetectCollisions(FrameworkElement player, FrameworkElement enemy)
{
    var rp = new Rect(Canvas.GetLeft(player), Canvas.GetTop(player), player.ActualWidth, player.ActualHeight);
    var re = new Rect(Canvas.GetLeft(enemy), Canvas.GetTop(enemy), enemy.ActualWidth, enemy.ActualHeight);
    rp.Intersect(re);
    return rp;
}

如果玩家和敌人发生碰撞,该方法将存储新的交集 Rect 到玩家 rect 变量,而不是 return Rect.Empty 结构。

foreach (var item in enemyList)
{
  var rect =  DetectCollisions(Player, item);
    if (!rect.IsEmpty)
    {
        MyCanvas.Children.Remove(item);
    }
}