Skip to content

Instantly share code, notes, and snippets.

@kurtdekker
Created March 2, 2023 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurtdekker/7736b0be45cc7f52ba7981c79eb4726c to your computer and use it in GitHub Desktop.
Save kurtdekker/7736b0be45cc7f52ba7981c79eb4726c to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// @kurtdekker - making a structural grid in Unity3D
// to use: drop this in a blank scene and watch!
//
// NOTE: this makes a web with a central link.
// you could do other connectivity strategies obviously.
public class MakeStructuralGrid : MonoBehaviour
{
void Start ()
{
// make a floor to bang down on
GameObject floor = GameObject.CreatePrimitive( PrimitiveType.Cube);
DestroyImmediate( floor.GetComponent<Collider>());
floor.transform.position = new Vector3( 0, -4.5f, 0);
// tilt the floor a bit
floor.transform.rotation = Quaternion.Euler( 0, 0, Random.Range( -5.0f, 5.0f));
floor.transform.localScale = new Vector3( 16, 1, 1);
floor.AddComponent<BoxCollider2D>();
// chose a random angle for the dropped chunk
float angle = Random.Range( 0.0f, 360.0f);
Quaternion rotation = Quaternion.Euler( 0, 0, angle);
int across = 5;
int down = 3;
int centerx = across / 2;
int centery = down / 2;
Rigidbody2D[,] bodyGrid = new Rigidbody2D[across,down];
// make and record all bodies
for (int j = 0; j < down; j++)
{
for (int i = 0; i < across; i++)
{
int x = i - across / 2;
int y = j - down / 2;
Vector3 position = new Vector3( x, y);
position = rotation * position;
position += Vector3.up * 4.0f;
GameObject chunk =GameObject.CreatePrimitive( PrimitiveType.Sphere);
DestroyImmediate( chunk.GetComponent<Collider>());
chunk.transform.position = position;
chunk.AddComponent<CircleCollider2D>();
Rigidbody2D rb2d = chunk.AddComponent<Rigidbody2D>();
bodyGrid[i,j] = rb2d;
}
}
Rigidbody2D centerBody = bodyGrid[centerx, centery];
// connect them to the center one!
for (int j = 0; j < down; j++)
{
for (int i = 0; i < across; i++)
{
Rigidbody2D body = bodyGrid[i,j];
if (i == centerx && j == centery)
{
// noop
}
else
{
FixedJoint2D fj = body.gameObject.AddComponent<FixedJoint2D>();
fj.connectedBody = centerBody;
fj.breakForce = 300;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment