- Home /
convert from world to voxel when 1 voxel doesn't equal 1 unity unit
I'm making a game which requires using a voxel engine to build structures, except I plan to include more models than just simple cubes, and some of these are quite small. So I need to the voxels to be smaller than 1 unity unit each (3 per unit). The problem is I'm having trouble converting between world space and voxel coordinates due to the unequal sizes (if they were the same size it wouldn't be a problem). This is what I've tried so far:
public Vector3 GetIndexFromWorld(Vector3 worldPos, Vector3 normals) {
float half = ((1f / (float)VoxelsPerMeter) / 2f); // VoxelsPerMeter equals 3
Vector3 localPos = transform.InverseTransformPoint(worldPos);
Vector3 point = localPos + normals * -half;
return new Vector3(Mathf.RoundToInt(point.x) * VoxelsPerMeter, Mathf.RoundToInt(point.y) * VoxelsPerMeter, Mathf.RoundToInt(point.z) * VoxelsPerMeter);
}
Thanks in advance for any help.
What's InverseTransformPoint for -- Do your objects run diagonally?
I have the InverseTransformPoint to convert from world space to the chunks local space, because the chunk contains the 3D array of voxels (and yea, to give the option of rotating the chunks).
Answer by whydoidoit · Mar 03, 2014 at 06:17 AM
Isn't it just:
var localPos = transform.InverseTransformPoint(worldPos) * VoxelsPerMeter;
return new Vector3(Mathf.FloorToInt(localPos.x),Mathf.FloorToInt(localPos.y),Mathf.FloorToInt(localPos.z));
Though I'd prefer a Tuple for the index.
Tuple<int,int,int>
Thanks whydoidoit. multiplying the local position by three, replacing "RoundToInt" with "FloorToInt", and removing the * VoxelsPer$$anonymous$$eter
from the final vector3 solved it.
Will convert this lot to an answer so you can tick it :)
How would you figure out how many voxels per meter? If the object scales, won't that change?? @nug700 @whydoidoit
It's not really something to "figure out" so much as it's something to be defined. Essentially, you could think of it as the reciprocal of uniform scale (where that scale would simply need to be an integer). If it's 8 local units per world unit, then you have 0.125 scale (1/8) and, by extension, 8 voxelsPerMeter by this example.
Do you think you could check out this question? https://answers.unity.com/questions/1817469/get-voxel-intensities-by-location.html Thank you!
Your answer
Follow this Question
Related Questions
Ingame voxel terrain manipulation(sorry for last post) 2 Answers
Need help with strategy terrain. 1 Answer
Voxel Terrains 0 Answers
Rounding edges of cubes (Voxels and Marching Cubes) 1 Answer
what has gone wrong with this script 1 Answer