Last active
August 29, 2015 13:59
-
-
Save lucatk/10909261 to your computer and use it in GitHub Desktop.
Class for serializing Locations (Bukkit)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
import org.bukkit.Bukkit; | |
import org.bukkit.Location; | |
import org.bukkit.World; | |
import org.bukkit.configuration.serialization.ConfigurationSerializable; | |
import org.bukkit.util.NumberConversions; | |
public class LocationSerializable extends Location implements ConfigurationSerializable { | |
public LocationSerializable(World world, double x, double y, double z) { | |
super(world, x, y, z); | |
} | |
public LocationSerializable(World world, double x, double y, double z, float yaw, float pitch) { | |
super(world, x, y, z, yaw, pitch); | |
} | |
public LocationSerializable(String world, double x, double y, double z) { | |
super(Bukkit.getWorld(world), x, y, z); | |
} | |
public LocationSerializable(String world, double x, double y, double z, float yaw, float pitch) { | |
super(Bukkit.getWorld(world), x, y, z, yaw, pitch); | |
} | |
public Map<String, Object> serialize() { | |
Map<String, Object> map = new HashMap<String, Object>(); | |
map.put("world", super.getWorld().getName()); | |
map.put("x", super.getX()); | |
map.put("y", super.getY()); | |
map.put("z", super.getZ()); | |
if(super.getYaw() != 0) map.put("yaw", super.getYaw()); | |
if(super.getPitch() != 0) map.put("pitch", super.getPitch()); | |
return map; | |
} | |
public static LocationSerializable deserialize(Map<String, Object> map) { | |
if(!isValid(map)) return null; | |
return new LocationSerializable(Bukkit.getWorld(String.valueOf(map.get("world"))), | |
NumberConversions.toDouble(map.get("x")), | |
NumberConversions.toDouble(map.get("y")), | |
NumberConversions.toDouble(map.get("z")), | |
map.containsKey("yaw") ? NumberConversions.toFloat(map.get("yaw")) : 0, | |
map.containsKey("pitch") ? NumberConversions.toFloat(map.get("pitch")) : 0); | |
} | |
private static boolean isValid(Map<String, Object> map) { | |
return map.containsKey("x") && map.containsKey("y") && map.containsKey("z"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Add this in your main class: | |
static { | |
ConfigurationSerialization.registerClass(LocationSerializable.class); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment