Continuing what we started, bringing the NPCs into the new CellLoc reality.
First Impression
Yesterday we moved the map to the new CellLoc coordinates, leaving the NPCs floating around looking foolish. To fix that, we’ll need to expand the CellLoc struct’s capabilities.
[System.Serializable]
publicstructCellLoc {
publicshort x;
publicshort y;
publicint z;
publicshort idx; // index of this space in the cell (zero-based)
publicshort dim; // number of subcells on a row, and also number of rows
public CellLoc(short x, short y, int z) {
this.x = x; this.y = y; this.z = z;
this.idx = 0; this.dim = 1;
}
public CellLoc(int x, int y, int z) {
this.x = (short) x; this.y = (short) y; this.z = z;
this.idx = 0; this.dim = 1;
}
}
publicclassCLUtils {
publicstatic Vector3 CellLocToVector3(CellLoc c, int layer) {
// note: layer 0 for ground, 1 for characters, etc
if (c.dim == 1) { // the simple case
returnnew Vector3((1f) * c.x,
(-1f) * c.y,
(-0.1f) * (c.z + layer));
} else {
Vector3 position;
int xPos = c.idx % c.dim;
int yPos = c.idx / c.dim;
position.x = c.x - 0.5f; // left side
position.x += (1f / (c.dim * 2f)); // first position
position.x += xPos * (1f / c.dim);
position.y = c.y - 0.5f; // top side
position.y += (1f / (c.dim * 2f)); // first position
position.y += yPos * (1f / c.dim);
position.y *= -1f;
position.z = (-0.1f) * (c.z + layer);
return position;
}
}
}
Changing the index to zero-based cleaned up the math a bit, although it’s still definitely subject to improvement. We also take a layer in the conversion method to tweak the z-value.
That [System.Serializable] line is to allow a CellLoc to show up in the Unity editor, just like a Vector3 would:
Now we can see, and even manipulate, a public CellLoc in a script
As with the map, there were many changes to get from Vector3 to CellLoc. Notably, UpdateNpcCohab is much simplified:
privatevoid UpdateNpcCohab() {
foreach (CellLoc cell in cellsContainingNpcs.Keys) {
int population = cellsContainingNpcs[cell].Count;
// print("Cell " + cell + " has an NPC population of " + population);
short dimension = (short) Math.Ceiling(Math.Sqrt(population));
short idx = 0;
foreach (int npcId in cellsContainingNpcs[cell]) {
npcScripts[npcId].newScale = new Vector3(1.0f/dimension, 1.0f/dimension, npcScripts[npcId].transform.localScale.z);
npcScripts[npcId].cell.idx = idx;
npcScripts[npcId].cell.dim = dimension;
npcScripts[npcId].newPosition = CLUtils.CellLocToVector3(npcScripts[npcId].cell, 1);
idx += 1;
}
}
}
We’re still updating newPosition along with the cellular location, for now. How do we look?
I guess we need to invert these textures too
Sorry for the short blog today. Trying to keep in good health, despite the weather and coworkers trying to make me sick, by getting a little extra rest.