-3

I ran into a problem while working on my platform game (once again :D) and i couldn't really found solution for it.. so here is the code:

Blocks.AddRange(this.Controls.OfType<PictureBox>());
if (Blocks.Any(x => x.Location.Y - Player.Height <= Player.Location.Y))
{
    Player.Top = Height - ClosestBlock.Location.Y - Player.Height;
}

and I need to detect which Block is the closest to move player on. If you have any ideas please let me know, Thanks!

Rob
  • 26,989
  • 16
  • 82
  • 98
P. Pett
  • 7
  • 2

1 Answers1

0

Check out the Phytagorean theorem.

If you have two points (x1, y1) and (x2, y2), then the distance between the two are distance = Math.Sqrt(Math.Pow((x2-x1), 2) + Math.Pow(y2-y1),2))

Iterate over all blocks, calculate their center-position (x2, y2) and use the Phytagorean theormen to find the distance between player center-position (x1, y1) and each block (x2n, y2n). Select the block with the shortest distance.

Frode
  • 3,325
  • 1
  • 22
  • 32