I have a method that creates a wall and uses the parameter Location l
. This is triggered when a snowball hits a block or person and creates the wall along the X
or Z
axes. My problem is that if I use Location l
, I can't use Player p
to get which direction the player is facing and rotate the wall along the X
and Z
axes accordingly. If I use Player p
, I can't find the Location
of the block hit by the snowball. So to solve my dilemma, I used Location l
and for when Player p
was needed I looped through all online player locations and find a player who was at Location l
and then casted it to Player p
.
My Code:
public static void wall(Location l){
Player p = null;
for(Player players: Bukkit.getOnlinePlayers()){
if (players.getLocation().equals(l)){
p = players;
}
else{
return;
}
}
My Questions:
Is this a valid solution to the issue? Was it valid but did I do it incorrectly? Is there a better way to solve the problem?
Thanks in advance!
One solution could be extending Location to keep track of the player(s) that are at that location.
public static void wall(Location l) {
List<Player> pList = l.getPlayers();
for(Player p : pList) {
//do Something
}
}
Since you're already storing Location in Player, you can update the values whenever the player moves to a new location.
Another solution would be to maintain a Map of Locations and Players
Map <Location, Set<Player>> locationPlayerMap //or
Map <Player, Location> playerLocationMap
Determining which solution is the best really comes down to factors like: "How Many Players are going to be on a Server", "How many Locations are there", "Are Multiple Players Allowed at a single Location", etc...
EDIT: You can also structure your method like the following:
public static void wall(Object o) {
if(o instanceof Player) {
//Snowball hit a player, use the direction they are facing and location
} else if(o instanceof Location) {
//Showball hit a Location, use some other factor.
}
}