- Home /
Vector 3 to float eg V3(1, 2, 3) -> float 123 in JS?
Hi everyone,
We are doing some programming where we need to generate a float seed based of a vector 3 value, is there any efficient/simple way of taking a Vector3 such as Vector3(1, 2, 3) and turning it into a float 123?
Similar to @YourGamesBeOver 's answer: Access each x,y,z value using this[int]; where [int] is an index 0,1,2, for x,y,z.
using UnityEngine; using System.Collections;
public class Example : $$anonymous$$onoBehaviour {
public Vector3 seedVector = new Vector3(1,2,3);
void Example() {
float seed = (seedVector[0]*100) + (seedVector[1]*10) + (seedVector[2]);
}
}
Another alternative is to create a string from the vector using ToString(), then converting the string to a float... but I don't know if that is good coding practice.
Well, it's almost what I needed...but this will work just as well!
In theory bitshifting would have worked better, but, it's not needed for what I require:
Vector3(100, 20, 30) -> float : 1002030
Vector3(100 100, 20 10, 30) = Vector3(10000, 200, 30) = 10,230
It's close, but it's perfect for what I need, even a vector with the same values in a different order will produce different results:
Vector3(20 100 (+), 30 10 (+), 100) = 2400;
Thanks guys!
Answer by YourGamesBeOver · Mar 21, 2014 at 02:17 PM
there are numerous solutions: If the components of the vector are single digits, you could multiply them by 100,10,1 and then add them together:
seed = vector.x*100+vector.y*10+vector.z;
Actually, that solution works for any number of digits, you could just change the scalars
If you don't actually care about what the final value is, you could use bitshifting.
I'm not too sure of the syntax in C# or js (most of my knowledge is in Java), but it'd be something like this: seed = vector.x<<16|vector.y<<8|vector.z; derp... I just remembered you can't bitshift floats (at least in c#), you could make them ints first...
Hopefully if I haven't answered your question, I at least gave you some ideas!