-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathSpatialHash.cs
More file actions
139 lines (115 loc) · 3.16 KB
/
Copy pathSpatialHash.cs
File metadata and controls
139 lines (115 loc) · 3.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
namespace SimplexCore
{
public class SpatialHash
{
public Dictionary<int, List<GameObject>> Hash = new Dictionary<int, List<GameObject>>();
public int CellSize;
public int Cols;
public int Rows;
List<int> ids = new List<int>();
private int x = 0;
private int y = 0;
Rectangle kk = Rectangle.Empty;
List<GameObject> nearby = new List<GameObject>();
Rectangle rect2 = Rectangle.Empty;
public SpatialHash()
{
Cols = 20;
Rows = 20;
CellSize = 128;
for (int i = 0; i < Cols * Rows; i++)
{
Hash.Add(i, null);
}
}
public void Clear()
{
// Hash.Clear();
for (int i = 0; i < Cols * Rows; i++)
{
if (Hash[i] != null)
{
Hash[i].Clear();
}
}
}
public void RegisterObject(GameObject go)
{
foreach (int item in GetIdsForObject(go))
{
if (Hash[item] == null)
{
Hash[item] = new List<GameObject>();
}
Hash[item].Add(go);
}
}
public void UnregisterAll()
{
foreach (var k in Hash)
{
if (k.Value != null)
{
k.Value.Clear();
}
}
}
public void UnregisterObject(GameObject go)
{
foreach (var k in Hash)
{
if (k.Value != null && k.Value.Contains(go))
{
k.Value.Remove(go);
}
}
}
public List<int> GetIdsForObject(GameObject go)
{
ids.Clear();
x = 0;
y = 0;
int max = Cols * Rows;
int max2 = Cols * CellSize;
for (int i = 0; i < max; i++)
{
kk.X = (int) go.Position.X - 64;
kk.Y = (int) go.Position.Y - 64;
kk.Width = 128;
kk.Height = 128;
rect2.X = x;
rect2.Y = y;
rect2.Width = CellSize;
rect2.Height = CellSize;
if (kk.Intersects(rect2))
{
ids.Add(i);
}
x += CellSize;
if (x >= max2)
{
x = 0;
y += CellSize;
}
}
return ids;
}
public List<GameObject> ObjectsNearby(GameObject go)
{
nearby.Clear();
foreach (int item in GetIdsForObject(go))
{
if (Hash[item] == null)
{
Hash[item] = new List<GameObject>();
}
nearby.AddRange(Hash[item]);
}
return nearby;
}
}
}