Let's take Box2d basics project and modify it to allow dragging and throwing ball around. We'll put all contents inside init method.

For that, when creating ball object, we now need to store it in a variable for future reference:

--create ball
self.ball = self:ball(100, 100)

We also need couple of additioanl object, one to store joint between mouse and ball and other is a dummy Box2d body to use in joint (because joints can be created only between box2d bodies)

--create empty box2d body for joint
--since mouse cursor is not a body
--we need dummy body to create joint
local ground = self.world:createBody({})
	
--joint with dummy body
local mouseJoint = nil

Now we need to handle three states:

  • when screen is touched or mouse down
  • when touch is moved or mouse move
  • when touch is released or mouse up

On mouse down, we simply create a joint between dummy body and ball:

-- create a mouse joint on mouse down
function self:onMouseDown(event)
	if self.ball:hitTestPoint(event.x, event.y) then
		local jointDef = b2.createMouseJointDef(ground, self.ball.body, 
		event.x, event.y, 100000)
		mouseJoint = self.world:createJoint(jointDef)
	end
end

On mouse move, we move ball where mouse cursor moved:

-- update the target of mouse joint on mouse move
function self:onMouseMove(event)
	if mouseJoint ~= nil then
		mouseJoint:setTarget(event.x, event.y)
	end
end

And when mouse is released, we should release ball object by destroying joint:

-- destroy the mouse joint on mouse up
function self:onMouseUp(event)
	if mouseJoint ~= nil then
		self.world:destroyJoint(mouseJoint)
		mouseJoint = nil
	end
end

And last, we need to register all mouse events:

-- register for mouse events
self:addEventListener(Event.MOUSE_DOWN, self.onMouseDown, self)
self:addEventListener(Event.MOUSE_MOVE, self.onMouseMove, self)
self:addEventListener(Event.MOUSE_UP, self.onMouseUp, self)

As a result we can throw this ball around as we want

Download sample Gideros project and try it yourself. ;)