public sealed partial 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;
}
(i tried to do if statment like this but it didnt work.)-
if (Canvas.GetLeft(Player) == Canvas.GetLeft(Enemy) &&
Canvas.GetTop(Player) == Canvas.GetTop(Enemy))
CodePudding user response:
How do i make a collision between my player and enemy?
You can use Intersect
method to determine if elements has common points. For example
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;
}
If player and enemy has collision, the method will store new intersection Rect to player rect variable, instead of this it return Rect.Empty
structure.
foreach (var item in enemyList)
{
var rect = DetectCollisions(Player, item);
if (!rect.IsEmpty)
{
MyCanvas.Children.Remove(item);
}
}