Gear are being driven by physics from the left-most gear (motor) and a combination of gear joints. I’m not setting angular velocity manually.
Gears are created dynamically… Below is an excerpt of creating the physics bodies:
newGear.physicsParams = {radius = newGear.radius, density=10, friction=1, bounce=0.001, filter = gearFilter} physics.addBody(newGear, "dynamic", newGear.physicsParams) --Set physics params consistently newGear.angularDamping = 0 newGear.linearDamping = 0 --Gear collision handler newGear.collision = GearCollisionListener newGear:addEventListener( "collision" ) newGear:addEventListener( "touch", GearTouchHandler ) table.insert(gearPuzzle.gears, newGear) gearPuzzle.groupMain:insert( newGear )
Each time a gear connected to one that has been connected to the motor, a Gear Joint is created between the two. Below is an excerpt from the GearCollisionListener() function:
--If gear initiating collision is on axle and then create a gear joint between the two gears --Will only fire if both gears are "pinned" to wall/axle (pivotJoint exists) if (#self.gearJoints == 0 and (self.pivotJoint ~= nil and event.other.pivotJoint ~= nil)) then --Need to delay physics calls when inside listeners function CreateGearJoint() print("GEAR PUZZLE: GEAR JOINT CREATED!!") if (self.pivotJoint ~= nil and event.other.pivotJoint ~= nil) then --Make sure both gears know about joint (so both can be removed when gear is removed) local gearJoint = physics.newJoint("gear", event.other, self, event.other.pivotJoint, self.pivotJoint, 1) self.gearJoints[#self.gearJoints+1] = gearJoint event.other.gearJoints[#event.other.gearJoints+1] = gearJoint AdjustGearLoopVolume() --Add to master joint tracker for easy cleanup table.insert(gearPuzzle.joints, gearJoint) end end timer.performWithDelay( 50, CreateGearJoint, 1 ) end
Each object keeps track of its own Gear Joints, so total angular velocity is being calculated like this:
local numGearsInMotion = 0 local totalAnglularVelocity = 0 for i,gear in pairs(gearPuzzle.gears) do if (#gear.gearJoints \> 0) then numGearsInMotion = numGearsInMotion + 1 totalAnglularVelocity = totalAnglularVelocity + math.floor(math.abs(gear.angularVelocity)) end end
One weird thing I’ve noticed is that once the gears have stopped, every gear I add or remove to the chain adds or removes “29” to/from the angular velocity:
https://gyazo.com/9060746dc85588ec6f1f61e15841fba1