Skip to content

Instantly share code, notes, and snippets.

@jmiskovic
Last active May 1, 2023 14:27
Show Gist options
  • Save jmiskovic/4f7ab8e1997fa09c7202dbdb1ccc0c9e to your computer and use it in GitHub Desktop.
Save jmiskovic/4f7ab8e1997fa09c7202dbdb1ccc0c9e to your computer and use it in GitHub Desktop.
LOVR collider mouse drag
-- LOVR demo: Creates a few hundred colliders and allows to drag them around using the right mouse button
-- Dependencies:
-- lovr-mouse.lua from https://github.com/bjornbytes/lovr-mouse/
-- mousearm.lua from https://github.com/jmiskovic/lovr-mousearm
-- phywire.lua from https://github.com/jmiskovic/lovr-phywire
local mousearm = require'mousearm'
local phywire = require'phywire'
local world = lovr.physics.newWorld(0,0,0, false)
world:setLinearDamping(0.1)
world:setAngularDamping(0.1)
local mouse_collider = world:newSphereCollider(0,0,0, 0.001)
mouse_collider:setKinematic(true)
mouse_collider:getShapes()[1]:setSensor(true)
local hovered = {}
local function randomQuaternion(q)
q = q or quat()
local u,v,w = math.random(), math.random(), math.random()
-- from "Uniform random rotations" in Graphic Gems III by K. Shoemake
q:set(math.sqrt(1-u)*math.sin(2*v*math.pi),
math.sqrt(1-u)*math.cos(2*v*math.pi),
math.sqrt(u)*math.sin(2*w*math.pi),
math.sqrt(u)*math.cos(2*w*math.pi),
true ) -- Raw components
return q
end
for i=1,500 do
local c = world:newBoxCollider(
lovr.math.randomNormal(50, 0),
lovr.math.randomNormal(50, 0),
lovr.math.randomNormal(50, 0),
2,
2,
2 + 3 * lovr.math.random())
c:setOrientation(randomQuaternion())
local c = world:newSphereCollider(
lovr.math.randomNormal(50, 0),
lovr.math.randomNormal(50, 0),
lovr.math.randomNormal(50, 0),
1,
2 + 3 * lovr.math.random())
c:setOrientation(randomQuaternion())
end
function lovr.update(dt)
world:update(1/60)
mouse_collider:setPose(lovr.headset.getPose('left'))
end
function lovr.draw(pass)
pass:text(lovr.timer.getFPS(), 0, 1, -0.5, 0.05)
pass:text(phywire.drawn_shapes or 0, 0, 1.1, -0.5, 0.05)
phywire.draw(pass, world, phywire.render_shapes)
local ray = mousearm.getRay()
world:raycast(ray.origin, ray.target,
function(shape, x, y, z)
local minx, maxx, miny, maxy, minz, maxz = shape:getAABB()
local cx, wx = (minx + maxx) / 2, maxx - minx
local cy, wy = (miny + maxy) / 2, maxy - miny
local cz, wz = (minz + maxz) / 2, maxz - minz
pass:box(cx, cy, cz, wx, wy, wz, 0, 0,0,0, 'line')
hovered.x, hovered.y, hovered.z = x, y, z
hovered.collider = shape:getCollider()
end)
end
function lovr.mousepressed(x, y, button)
if button == 2 and hovered.collider then
lovr.physics.newBallJoint(mouse_collider, hovered.collider, hovered.x, hovered.y, hovered.z)
end
end
function lovr.mousereleased(x, y, button)
for _, joint in ipairs(mouse_collider:getJoints()) do
joint:destroy()
end
hovered = {}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment