Java HashMap - String to bukkit Vector? How?

456 views Asked by At

I really didn't see anything that answered my question and now I'm stuck. The gist of it is that I'm storing a Vector inside a HashMap as a string, like so:

notes.put(notes.size()+1), player.getLocation().getDirection().toString());

notes is my HashMap name. Since HashMaps seemingly only store strings, I need a way to convert it back to a Vector.

Later in my code, I implement the vector later like this:

`player.getLocation().setDirection(vector);`

When I couldn't think of a way around the conversion, I tried this mathematical way of calculating the direction facing like so:

`double pit = ((parsed[4]+ 90) * Math.PI) / 180;
double ya = ((parsed[3]+ 90) * Math.PI) / 180;
double newX = Math.sin(pit) * Math.cos(ya);
double newY = Math.sin(pit) * Math.sin(ya);
double newZ = Math.cos(pit);
Vector vector = new Vector(newX, newZ, newY);`

pit being the pitch and ya being the Yaw. parsed[3] and parsed[4] is just my original Pitch and Yaw of the player. Again this didn't work and sent this error to the server console. [ERROR]: null. In short, I just want a way to convert a String to a Vector. I'd prefer not to do it the math way but if I don't have a choice, so be it. ANY help and constructive criticism is appreciated; Thanks in advance!

As a side note: I'm fairly new to Java but I do have experience in C and JavaScript, so a lot of things are familiar to me.

1

There are 1 answers

0
Jojodmo On

HashMaps aren't limited to storing strings. They can store any Object, including Vectors

Map<Integer, Vector> myMap = new HashMap<Integer, Vector>();

So, instead of worrying about converting a String to a Vector, you could simply store vectors in your HashMap

Map<Integer, Vector> notes = new HashMap<Integer, Vector>();

//add a vector to the map
notes.put(notes.size() + 1, player.getLocation().getDirection());

//get a vector out of the map
Vector playerVector = notes.get(notes.size());

Also, with the way you're currently writing it, you could simply use an ArrayList

List<Vector> notes = new ArrayList<Vector>();

//add a vector to the array
notes.add(player.getLocation().getDirection());

//get a vector out of the map
Vector playerVector = notes.get(notes.size());

If you really would like to change the String to a Vector for some reason, you could use

//get the x, y, and z values of the vector as an Array
String[] components = vectorString.split(",");

//components[0] will be the x value, [1] will be y, and [2] will be z.
double x = Double.valueOf(components[0]);
double y = Double.valueOf(components[1]);
double z = Double.valueOf(components[2]);

//construct the vector using the components
Vector myVector = new Vector(x, y, z);