- Home /

# Looking for some help with a QuadTree implementation.

I will preface this by saying I know there are hundreds of tutorials out there on quadtrees etc but I wanted to try to create my own as I am an amateur looking to learn random things and struggle to learn without attempting my own implementations then using references to improve then.

Anyway, I am trying to implement a quadtree that starts with a triangle:

the main reason is for LOD based updating. However, with my current implementation I have some issues. Predominately with removal of subtriangles.

Here are the two parts of the code necessary for it to work:

Testing of nodes and the node definitions

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Monobeviour testing Nodes.
public class QuadTreeMWE : MonoBehaviour
{
NodeMWE treeRoot;
Mesh mesh;
Vector3 currentPoint;
int zDepth = 10;
void Start()
{
mesh = GetComponent<MeshFilter>().mesh = new Mesh();
Vector3 testa = new Vector3(5, 5, 0);
Vector3 testb = new Vector3(0, 5, 0);
Vector3 testc = new Vector3(5, 0, 0);
treeRoot = new NodeMWE(testa, testb, testc);
mesh.vertices = treeRoot.GetVertices().ToArray();
mesh.triangles = treeRoot.GetTris();
}
int tempVertLength = 0;
void Update()
{
Vector3 mousePos = Input.mousePosition;
currentPoint = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 10));
currentPoint.z = zDepth;
treeRoot.UpdateDistance(currentPoint);
if(Input.GetKeyDown(KeyCode.Minus))
{
zDepth--;
}
if(Input.GetKeyDown(KeyCode.Plus))
{
zDepth++;
}
mesh.vertices = treeRoot.GetVertices().ToArray();
mesh.triangles = treeRoot.GetTris();
}
}
public class NodeMWE
{
int depth;
List<int> subTris;
//Holds Boundary/distance(ish) data for node
public TriangleMWE tri;
//Recuresively holds all vertices
private List<Vector3> vertices;
//Children
NodeMWE[] leaves;
bool isEndNode;
//Base Leaf Declaration
public NodeMWE(Vector3 a, Vector3 b, Vector3 c)
{
vertices = new List<Vector3>{a, b, c};
tri = new TriangleMWE(new Vector3[]{vertices[0], vertices[1], vertices[2]}, new int[] {2, 1, 0});
isEndNode = true;
depth = 0;
}
//Non-Base Leafs
public NodeMWE(int a, int b, int c, List<Vector3> verts, int dpth)
{
depth = dpth;
vertices = verts;
tri = new TriangleMWE(new Vector3[]{vertices[a], vertices[b], vertices[c]}, new int[] {a, b, c});
isEndNode = true;
}
//Add or remove nodes based on distance from a point
public void UpdateDistance(Vector3 point)
{
float camDistance = tri.GetDistanceFromPointFactor(point);
if(camDistance > 5 || depth >= MeshParameters.maxDepth) {
if(isEndNode)
{
//Remove();
}
else
{
foreach(NodeMWE leaf in leaves)
{
leaf.UpdateDistance(point);
}
}
return;
}
if(isEndNode)
{
Add();
}
else
{
foreach(NodeMWE leaf in leaves)
{
leaf.UpdateDistance(point);
}
}
}
//Subdivides Node/creates Children
public void Add()
{
isEndNode = false;
subTris = new List<int>();
leaves = new NodeMWE[4];
int nextDepth = depth+1;
int vOffset = vertices.Count;
int[] tris = tri.GetTris();
Vector3 a = MeshHelpersMWE.FindCenterPoint(vertices[tris[0]], vertices[tris[1]]);
Vector3 b = MeshHelpersMWE.FindCenterPoint(vertices[tris[1]], vertices[tris[2]]);
Vector3 c = MeshHelpersMWE.FindCenterPoint(vertices[tris[2]], vertices[tris[0]]);
vertices.Add(a);
vertices.Add(b);
vertices.Add(c);
leaves[0] = new NodeMWE(tris[0], vOffset, vOffset+2, vertices, nextDepth);
leaves[1] = new NodeMWE(vOffset, vOffset+1, vOffset+2, vertices, nextDepth);
leaves[2] = new NodeMWE(vOffset+2, vOffset+1, tris[2], vertices, nextDepth);
leaves[3] = new NodeMWE(tris[1], vOffset+1, vOffset, vertices,nextDepth);
}
//UnSubs Node/removes Children
public bool Remove()
{
if(isEndNode)
{
return true;
}
else {
foreach(NodeMWE leaf in leaves)
{
if(leaf.Remove())
{
leaves = null;
isEndNode = true;
int[] verticesToRemove = leaf.tri.GetTris();
//vertices.RemoveAt(verticesToRemove[0]);
break;
}
}
return false;
}
}
//Get triangles to draw
public int[] GetTris()
{
if(isEndNode) { return tri.GetTris(); }
else{
subTris.Clear();
foreach(NodeMWE leaf in leaves)
{
subTris.AddRange(leaf.GetTris());
}
}
return subTris.ToArray();
}
//Get Vertices to draw
public List<Vector3> GetVertices()
{
return vertices;
}
}
public static class MeshParametersMWE
{
public static readonly int maxDepth = 3;
}
public static class MeshHelpersMWE
{
public static Vector3 FindCenterPoint(Vector3 a, Vector3 b)
{
float aPoint = (a.x + b.x)/2;
float bPoint = (a.y + b.y)/2;
float cPoint = (a.z + b.z)/2;
return new Vector3(aPoint, bPoint, cPoint);
}
}
```

Triangles used within Nodes: using System.Collections; using System.Collections.Generic; using UnityEngine;

```
public class TriangleMWE
{
Vector3[] vPoints;
Vector3 normal;
int[] tPoints;
Vector3 centerPoint;
float longestDistance;
public TriangleMWE(Vector3[] vecPoints, int[] triPoints)
{
vPoints = vecPoints;
tPoints = triPoints;
longestDistance = 0;
normal = Vector3.Cross(vPoints[1]-vPoints[0], vPoints[0]-vPoints[2]);
centerPoint = (vPoints[0] + vPoints[1] + vPoints[2])/3;
normal = Vector3.Normalize(normal);
foreach(Vector3 vec in vecPoints)
{
float vecDis = GetVecDistances(vec);
if(vecDis > longestDistance) { longestDistance = vecDis; }
}
}
public float GetVecDistances(Vector3 refPoint){
Vector3 s0 = refPoint - centerPoint;
s0.x = Mathf.Pow(s0.x, 2);
s0.y = Mathf.Pow(s0.y, 2);
s0.z = Mathf.Pow(s0.z, 2);
return Mathf.Sqrt(s0.x + s0.y + s0.z);
}
public float GetDistanceFromPointFactor(Vector3 refPoint){
Vector3 s0 = refPoint - centerPoint;
s0.x = Mathf.Pow(s0.x, 2);
s0.y = Mathf.Pow(s0.y, 2);
s0.z = Mathf.Pow(s0.z, 2);
return Mathf.Sqrt(s0.x + s0.y + s0.z)/longestDistance;
}
public int[] GetTris()
{
return tPoints;
}
}
```

Apologies for poor variable naming etc, hopefully someone can make sense of what I am trying to do here and tell me if it is as entirely idiotic as I think it is.

Now, trying to remove children causes issues because if I remove the vertices and the triangles - some vertices are shared and the triangles arrays all mess up because they are currently pointing at certain vertice indexes. However, if vertices are removed low down in the vertex array then all the other triangle arrays point to the wrong vertices. Any advice on how to perform this remove would be greatly appreciated as I have spent hours trying to work it out myself.

### Your answer

### Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.

### Follow this Question

### Related Questions

How to draw beams? 2 Answers

Can you tint a specific part of a 2D Sprite? 1 Answer

camera and positiong problems 1 Answer

How do you insert an image into the new rich text system? 1 Answer

How to rotate a quad based on another object's rotation? 0 Answers