Official Everybody Edits Forums

Do you think I could just leave this part blank and it'd be okay? We're just going to replace the whole thing with a header image anyway, right?

You are not logged in.

#1 2015-05-06 19:05:25

madiik
Member
From: floor above Yuuta
Joined: 2015-02-26
Posts: 514

[Question] Attempting to get nearest player with foreach.

Would this be correct?

case "m":
                    {
                        EEName Player = Players.Find(nm => nm.UserId == m.GetInt(0));
                        foreach (var TargetPlayer in PlayersPlaying)
                            if ((TargetPlayer.Physics.X - Player.Physics.X) < 16 && (TargetPlayer.Physics.Y - Player.Physics.Y) < 16) //-------ESPECIALLY THIS PART
                            {
                                //dostuff
                            }
                    }
                    break;

shh i have returned

Offline

#2 2015-05-07 12:15:32

DarkDragon4900
Member
Joined: 2015-03-17
Posts: 251

Re: [Question] Attempting to get nearest player with foreach.

public int Distance(Point point1, Point point2)
{
    return Math.Sqrt(
        Math.Pow(point2.X - point1.X, 2)
        +
        Math.Pow(point2.Y - point1.Y, 2)
        );
}

List<Player> Players = new List<Player>();
Players.Add(new Player(){Name = "darkdragon4900", Location = new Point(5, 5)});
Players.Add(new Player(){Name = "goeyfun", Location = new Point(10, 5)});
Player madiik = new Player(){Name = "madiik", Location = new Point(6, 5)};
Players.Add(madiik);

Player closestPlayer = FindClosestPlayer(madiik, Players);
Console.WriteLine("Closest player to madiik: {0}.", closestPlayer.Name);
Console.WriteLine("X: {0}, Y: {1}", closestPlayer.Location.X, closestPlayer.Location.Y);

public Player FindClosestPlayer(Player player, List<Player> players)
{
    Player p = new Player();
    int d;
    foreach (Player pl in players)
    {
        if (d == null)
        { p = pl; d = Distance(player.Location, pl.Location); }
        else
        {
            if (Distance(player.Location, pl.Location) < d)
            {
                p = pl;
                d = Distance(player.Location, pl.Location);
            }
        }
    }
    return p;
}

// Output:
// 
// Closest player to madiik: darkdragon4900.
// X: 5, Y: 5

Offline

DarkDragon49001430997332502130

Board footer

Powered by FluxBB

[ Started around 1732478830.1882 - Generated in 0.042 seconds, 10 queries executed - Memory usage: 1.36 MiB (Peak: 1.45 MiB) ]