| 1 |
require 'dokidoki.module' |
| 2 |
[[ make_polygon, collide, |
| 3 |
points_to_polygon, make_rectangle ]] |
| 4 |
|
| 5 |
local v2 = require 'dokidoki.v2' |
| 6 |
import(require 'dokidoki.base') |
| 7 |
|
| 8 |
|
| 9 |
local native = require 'collision.native' |
| 10 |
|
| 11 |
|
| 12 |
function make_polygon(vertices) |
| 13 |
if v2.cross(vertices[2] - vertices[1], vertices[3] - vertices[2]) < 0 then |
| 14 |
vertices = ireverse(vertices) |
| 15 |
end |
| 16 |
|
| 17 |
local coords = {} |
| 18 |
for _, v in ipairs(vertices) do |
| 19 |
table.insert(coords, v.x) |
| 20 |
table.insert(coords, v.y) |
| 21 |
end |
| 22 |
return {data = native.make_polygon(coords), vertices = vertices} |
| 23 |
end |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
function collide(body1, body2) |
| 29 |
|
| 30 |
local facing1 = body1.facing or v2.unit(body1.angle) |
| 31 |
local facing2 = body2.facing or v2.unit(body2.angle) |
| 32 |
|
| 33 |
local collision, x, y = native.collide( |
| 34 |
body1.pos.x, body1.pos.y, facing1.x, facing1.y, body1.poly.data, |
| 35 |
body2.pos.x, body2.pos.y, facing2.x, facing2.y, body2.poly.data) |
| 36 |
|
| 37 |
return collision and v2(x, y) |
| 38 |
end |
| 39 |
|
| 40 |
function points_to_polygon(points) |
| 41 |
local sum = v2(0, 0) |
| 42 |
for _, p in ipairs(points) do |
| 43 |
sum = sum + p |
| 44 |
end |
| 45 |
local pos = sum / #points |
| 46 |
local vertices = {} |
| 47 |
for _, p in ipairs(points) do |
| 48 |
table.insert(vertices, p - pos) |
| 49 |
end |
| 50 |
return pos, make_polygon(vertices) |
| 51 |
end |
| 52 |
|
| 53 |
function make_rectangle(w, h) |
| 54 |
return make_polygon{ |
| 55 |
v2(-w/2, -h/2), |
| 56 |
v2(w/2, -h/2), |
| 57 |
v2(w/2, h/2), |
| 58 |
v2(-w/2, h/2)} |
| 59 |
end |
| 60 |
|
| 61 |
return get_module_exports() |