This is basically the last and final piece of the puzzle I need to finish the game I’m trying to make. So I used the template code from the corona spaceship tutorial and made modifications and everything is working except sometimes I get the error: Attempt to perform arithmetic on field ‘touchOffsetX’ (a nil value). I’ve noticed that this only happens when the object that is drag-able is touched near it’s edge, otherwise everything usually works fine. Here’s the piece of code having the problem:
local function dragCircle( event ) local circle = event.target local phase = event.phase if ( "began" == phase ) then -- Set touch focus on the circle display.currentStage:setFocus( circle ) circle.touchOffsetX = event.x - circle.x circle.touchOffsetY = event.y - circle.y elseif ("moved" == phase) then circle.x = event.x - circle.touchOffsetX circle.y = event.y - circle.touchOffsetY elseif ("ended" == phase or "cancelled" == phase ) then display.currentStage:setFocus(nil) end return true end
Here’s some code on the actual object (the circle):
circle = display.newImageRect( mainGroup, "circle.png", 15, 15) circle.myName = "circle" physics.addBody(circle, {isSensor=true, radius=7.5}) circle.gravityScale = 0 circle.x = display.contentCenterX circle.y = display.contentHeight-25
and the event listener located in the scene:show:
circle:addEventListener("touch", dragCircle)
I tried a few solutions like changing the radius, but I just don’t get why touching the outer edge of the circle would cause this error, assuming that is the cause, unless I’m totally wrong. Thanks again in advance!