Finding actual location of player's bed/anchor

Discussion in 'Plugin Development' started by MixerBlaze, Aug 5, 2021.

Thread Status:
Not open for further replies.
  1. Offline

    MixerBlaze

    Hello,
    For a long time now I've been trying to figure out how to find the location of a bed/anchor, in order to save these locations, and then apply it back to the player at a later time. (The plugin I am developing saves each player's state in each world, and then applies them back to the player on return to the world.)
    Currently, I'm using a very hacky workaround to save these locations (involving running checks each time the player clicks a bed/anchor). I would like to improve this and just know the actual location so I can setBedLocation.
    Someone in a Discord server wrote some code for me to consider although I don't completely understand what it does. I'll post it in case it is of any help.
    Code:
        public Location getRespawnPoint(Player player) {
            EntityPlayer nmsPlayer = ((CraftPlayer) player).getHandle();
            BlockPosition spawn = nmsPlayer.getSpawn();
            if (spawn == null) return null;
            String dimension = nmsPlayer.getSpawnDimension().a().getKey();
            org.bukkit.World.Environment environment = dimension.equalsIgnoreCase("overworld") ?
                    org.bukkit.World.Environment.NORMAL : (dimension.equalsIgnoreCase("the_nether") ?
                    org.bukkit.World.Environment.NETHER : org.bukkit.World.Environment.THE_END);
            Location respawnPoint = null;
            for (World world : Bukkit.getWorlds()) {
                if (world.getEnvironment() == environment) {
                    respawnPoint = new Location(world, spawn.getX(), spawn.getY(), spawn.getZ());
                    break;
                }
            }
            return respawnPoint;
        }
     
  2. Offline

    Tim_M

    Have you tried
    Code:
    player.getBedSpawnLocation()
    
    You can save that to a Map that has the player's uuid and location. For each world you can have a map with the same name, and then get them by *world.
    Example:
    Code:
    Map<World, Map<UUID, Location>> spawnPoints = new HashMap<>();
    
    Or
    Code:
    Map<String, Map<UUID, Vector>> spawnPoints = new HashMap<>();
    
     
    Last edited: Aug 11, 2021
Thread Status:
Not open for further replies.

Share This Page