I’m interested in implementing Conway’s Game of Life in Unity. If I have an array, say 1K square, of values that have two states (true/false 1/0, etc) how could I translate that to a display of a pixel grid?
Do you want 2d or 3d? If you feel the need for 3d… you could instantiate 100000 blocks … but that might be really slow.
In 2d… I never work with 2d… but you could create three square images… and place them on the screen according to what the state of that square is supposed to be.
Finally, you could create a texture and use setpixels to set the pixels of the texture to the appropriate colors depending on their state.
Those are my best suggestions. Good luck!
Thanks for the reply. I was thinking 2D. I’ll look into setpixels for a texture, sounds like the way to go.
Not super-optimized or anything, but:
#pragma strict
var size = 500;
var timeDelay = 0.25;
var populateThreshold = 0.2;
var liveColor = Color.white;
var deadColor = Color.black;
function Start () {
var grid = [new boolean[size*size], new boolean[size*size]];
for (var i = 0; i < size*size; i++) {
if (Random.value < populateThreshold) {
grid[0][i] = true;
}
}
var tex = new Texture2D(size, size);
tex.filterMode = FilterMode.Point;
GetComponent (Renderer).material.mainTexture = tex;
var pixels = new Color32[size*size];
var neighborsX = [-1, 0, 1, -1, 1, -1, 0, 1];
var neighborsY = [-1, -1, -1, 0, 0, 1, 1, 1];
var gridIndex = 0;
var gridIndex2 = 1;
while (true) {
for (var y = 0; y < size; y++) {
for (var x = 0; x < size; x++) {
var count = 0;
for (i = 0; i < neighborsX.Length; i++) {
if (HasNeighborAt (x + neighborsX[i], y + neighborsY[i], grid[gridIndex])) {
count++;
}
}
var pos = x + size*y;
if (grid[gridIndex][pos]) {
if (count < 2 || count > 3) {
grid[gridIndex2][pos] = false;
pixels[pos] = deadColor;
}
else {
grid[gridIndex2][pos] = true;
pixels[pos] = liveColor;
}
}
else {
if (count == 3) {
grid[gridIndex2][pos] = true;
pixels[pos] = liveColor;
}
else {
grid[gridIndex2][pos] = false;
pixels[pos] = deadColor;
}
}
}
}
tex.SetPixels32 (pixels);
tex.Apply();
gridIndex = 1-gridIndex;
gridIndex2 = 1-gridIndex2;
yield WaitForSeconds (timeDelay);
}
}
function HasNeighborAt (x : int, y : int, grid : boolean[]) {
if (x < 0) {
x += size;
}
else if (x >= size) {
x -= size;
}
if (y < 0) {
y += size;
}
else if (y >= size) {
y -= size;
}
return grid[x + y*size];
}
–Eric
Thanks Eric, I’ll have a look at that. I’m exploring different implementations so that looks like a good starting point.