Last active
October 24, 2024 18:41
-
-
Save xenobrain/1bd3305c70f2bed1d786071ee4e60436 to your computer and use it in GitHub Desktop.
SAT
This file contains 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
def create_vertices rect | |
x = rect.x; y = rect.y | |
w = rect.w; h = rect.h | |
cx = x + w * 0.5; cy = y + h * 0.5 | |
sin = Math.sin (rect.angle || 0.0).to_radians; cos = Math.cos (rect.angle || 0.0).to_radians | |
[ | |
[(x - cx) * cos - (y + h - cy) * sin + cx, (x - cx) * sin + (y + h - cy) * cos + cy], # Top Left | |
[(x + w - cx) * cos - (y + h - cy) * sin + cx, (x + w - cx) * sin + (y + h - cy) * cos + cy], # Top Right | |
[(x + w - cx) * cos - (y - cy) * sin + cx, (x + w - cx) * sin + (y - cy) * cos + cy], # Bottom Right | |
[(x - cx) * cos - (y - cy) * sin + cx, (x - cx) * sin + (y - cy) * cos + cy] # Bottom Left | |
] | |
end | |
def find_collision_obb_obb a, b | |
a = create_vertices a | |
b = create_vertices b | |
k = 0 | |
while k < 2 | |
a_len = a.length | |
b_len = b.length | |
i = 0 | |
while i < a_len | |
min_p = Float::INFINITY | |
v1x, v1y = a[(i+1)%a_len] | |
v0x, v0y = a[i] | |
nx = v0y - v1y | |
ny = v1x - v0x | |
j = 0 | |
while j < b_len | |
v1x, v1y = b[j] | |
p = (v1x-v0x)*nx + (v1y-v0y)*ny | |
min_p = p if p < min_p | |
j += 1 | |
end | |
return false if min_p >= 0 | |
i += 1 | |
end | |
t = a | |
a = b | |
b = t | |
k += 1 | |
end | |
true | |
end | |
def tick args | |
args.state.rect_a ||= { x: 100, y: 300, w: 200, h: 50, angle: 45, path: 'sprites/square/green.png' } | |
args.state.rect_b ||= { x: 400, y: 250, w: 100, h: 300, angle: 0, path: 'sprites/square/blue.png' } | |
args.state.rect_a.y += args.inputs.up_down | |
args.state.rect_a.x += args.inputs.left_right | |
args.state.rect_a.angle += 1 if args.inputs.keyboard.q | |
args.state.rect_a.angle -= 1 if args.inputs.keyboard.e | |
if find_collision_obb_obb args.state.rect_a, args.state.rect_b | |
args.state.rect_a.path = 'sprites/square/red.png' | |
else | |
args.state.rect_a.path = 'sprites/square/green.png' | |
end | |
args.outputs.sprites << args.state.rect_b | |
args.outputs.sprites << args.state.rect_a | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment