From f4346b8f06653dbc1e0c346d88f5f83ca8a7b876 Mon Sep 17 00:00:00 2001 From: sanine Date: Wed, 22 Mar 2023 23:06:40 -0500 Subject: re-implement bouncing ball --- main.lua | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) (limited to 'main.lua') diff --git a/main.lua b/main.lua index d6971b7..9f26eb3 100644 --- a/main.lua +++ b/main.lua @@ -6,11 +6,53 @@ local Vec3 = honey.Vec3 local Mat4 = honey.Mat4 local ecs = honey.ecs local systems = honey.standardSystems +local ode = honey.ode -- initialize honey local window = honey.init() +-- setup physics +local world = ode.WorldCreate() +local space = ode.HashSpaceCreate(ode.Space0) +ode.WorldSetGravity(world, 0, -10, 0) +ode.WorldSetCFM(world, 1e-5) +ode.CreatePlane(space, 0, 1, 0, 0) +local contactgroup = ode.JointGroupCreate(16) +local body = ode.BodyCreate(world) +local geom = ode.CreateSphere(space, 0.5) +local mass = ode.MassCreate() +ode.MassSetSphere(mass, 1, 0.5) +ode.BodySetMass(body, mass) +ode.GeomSetBody(geom, body) +ode.BodySetPosition(body, 0, 3, 0) + +function physicsStep() + ode.SpaceCollide(space, function(o1, o2) + local b1 = ode.GeomGetBody(o1) + local b2 = ode.GeomGetBody(o2) + local contact = ode.CreateContact{ + surface = { + mode = ode.ContactBounce + ode.ContactSoftCFM, + mu = ode.Infinity, + bounce = 1.0, + bounce_vel = 0.1, + soft_cfm = 0.001, + }, + } + local collisions = ode.Collide(o1, o2, 1) + if #collisions > 0 then + print("collision detected!") + ode.ContactSetGeom(contact, collisions[1]) + local joint = ode.JointCreateContact(world, contactgroup, contact) + ode.JointAttach(joint, b1, b2) + end + end) + ode.WorldQuickStep(world, 0.01) + ode.JointGroupEmpty(contactgroup) +end + + -- create camera matrices local camera = { view=Mat4():identity():translate(Vec3{0, 0, -60}), @@ -79,6 +121,19 @@ local groundPlane = { } level:addEntity(groundPlane) + +local ball = { + transform=Mat4():identity(), + parent=false, + mesh=icosa, + shader=shader, + update=function(self, dt) + local x, y, z = ode.BodyGetPosition(body) + self.transform:identity():translate(Vec3{x, y, z}) + end, +} +level:addEntity(ball) + -- close window on ESCAPE key window:setKeyCallback(function(_, key) if key == glfw.KEY_ESCAPE then @@ -97,6 +152,7 @@ honey.loop(window, function(dt) gl.ClearColor(0.2, 0.4, 1.0, 1.0) gl.Clear(gl.COLOR_BUFFER_BIT + gl.DEPTH_BUFFER_BIT) level:update(dt) + physicsStep() end) -- clean up -- cgit v1.2.1