Distance joint not getting removed

Hello everyone,

What I want to do is, a “distance” joint should be created on touch and it should be removed when the touch is over. But its not happening as expected please help me to overcome it. Following is the code:

local physics = require( "physics" ) physics.start() physics.setDrawMode( "hybrid" ) physics.setGravity(0,0) local bg=display.newRect( 0,0,display.contentWidth,display.contentHeight ) bg.anchorX=0 bg.anchorY=0 local myRect = display.newRect( display.contentWidth/2, 100, 50, 50 ) myRect:setFillColor( 1, 0, 0 ) local myCircle = display.newCircle( display.contentWidth/2, 200, 20 ) myCircle:setFillColor( 0, 0, 1 ) physics.addBody( myRect, "static") physics.addBody( myCircle,{density=0} ) function bg:touch(event) if (event.phase=="began") then local myJoint = physics.newJoint( "distance", myRect, myCircle, myRect.x, myRect.y, myCircle.x, myCircle.y) print("happened") elseif (event.phase=="ended") then display.remove( myJoint ) print( "ended" ) end end bg:addEventListener( "touch", bg )

Thanks in advance.

Your variable is out of scope by the time you try to remove it.

Try this:

function bg:touch(event) if (event.phase=="began") then myRect.myJoint = physics.newJoint( "distance", myRect, myCircle, myRect.x, myRect.y, myCircle.x, myCircle.y) elseif (event.phase=="ended") then display.remove( myRect.myJoint ) myRect.myJoint = nil end end

Sir @roaminggamer,

Thanks for the solution, the problem is solved. I understood what I was doing wrong.

Regards,

Swanand Thakur.

Your variable is out of scope by the time you try to remove it.

Try this:

function bg:touch(event) if (event.phase=="began") then myRect.myJoint = physics.newJoint( "distance", myRect, myCircle, myRect.x, myRect.y, myCircle.x, myCircle.y) elseif (event.phase=="ended") then display.remove( myRect.myJoint ) myRect.myJoint = nil end end

Sir @roaminggamer,

Thanks for the solution, the problem is solved. I understood what I was doing wrong.

Regards,

Swanand Thakur.