Last active
November 12, 2019 15:39
-
-
Save 01010111/dfb62837eaae991ea79454020e1eab63 to your computer and use it in GitHub Desktop.
Get Hitboxes from 2D Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import zero.utilities.IntPoint; | |
import zero.utilities.Rect; | |
class HitBox { | |
static function main() { | |
for (rect in make_hitboxes([ | |
[0, 0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0, 0], | |
[1, 1, 1, 0, 0, 0, 0, 0], | |
[1, 1, 1, 0, 0, 0, 1, 1], | |
[1, 1, 1, 0, 0, 0, 1, 1], | |
[1, 1, 1, 1, 1, 1, 1, 1], | |
[1, 1, 1, 1, 1, 1, 1, 1], | |
], [1])) trace(rect); | |
} | |
static function make_hitboxes(map:Array<Array<Int>>, solids:Array<Int>) { | |
var visited_nodes:Array<IntPoint> = []; | |
var check_map = (start:IntPoint, end:IntPoint, map:Array<Array<Int>>) -> { | |
var out = true; | |
var rect_nodes:Array<IntPoint> = [for (j in start.y...end.y + 1) for (i in start.x...end.x + 1) [i,j]]; | |
for (node in rect_nodes) { | |
if (!out) break; | |
if (solids.indexOf(map[node.y][node.x]) < 0) out = false; | |
for (vnode in visited_nodes) { | |
if (!out) break; | |
if (vnode.equals(node)) out = false; | |
} | |
} | |
for (node in rect_nodes) node.put(); | |
return out; | |
} | |
var make_rect = (map:Array<Array<Int>>, node:IntPoint) -> { | |
var start:IntPoint = node.copy(); | |
while (start.x > 0 && check_map(start - [1, 0], node, map)) start.x -= 1; | |
while (start.y > 0 && check_map(start - [0, 1], node, map)) start.y -= 1; | |
return { start: start, end: node }; | |
} | |
var nodes = [for (j in 0...map.length) for (i in 0...map[0].length) if (solids.indexOf(map[j][i]) >= 0) IntPoint.get(i, j)]; | |
var rects = []; | |
var i = 0; | |
while (nodes.length > 0) { | |
var node = nodes.pop(); | |
var rect = make_rect(map, node); | |
rects.push(rect); | |
for (n in [for (j in rect.start.y...rect.end.y + 1) for (i in rect.start.x...rect.end.x + 1) for (n in nodes) if (n.equals([i, j])) n]) { | |
nodes.remove(n); | |
n.put(); | |
} | |
node.put(); | |
} | |
var out = [for (rect in rects) Rect.get(rect.start.x, rect.start.y, rect.end.x - rect.start.x + 1, rect.end.y - rect.start.y + 1)]; | |
for (rect in rects) { | |
rect.start.put(); | |
rect.end.put(); | |
} | |
return out; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment