Detection When Touch Leaves Object

I have a module with a touch listener used to implement drag and drop functionality. It functions well, except when I drag the mouse quickly and the cursor leaves the object between frames (at least I think that’s what’s happening). The object is left wherever the cursor left it and my snap function is not called. Here is the relevant code:

[lua]

  –

  – snap

  – Moves object to the nearest grid point

  – @param xOffset - The horizontal distance between grid points

  – @param yOffset - The vertical distance between grid points

  –

  function object:snap(xOffset, yOffset)

    object.x = round(object.x / xOffset) * xOffset

    object.y = round(object.y / yOffset) * yOffset

  end

  –

  – hasnot

  – @param xPosition - the x-coordinate of the position to test

  – @param yPositon - the y-coordinate of the position to test

  – @return - true if the position is not within the object

  –  otherwise, false

  –

  function object:hasnot(xPosition, yPosition)

    local bounds = object.contentBounds

    return (xPosition < bounds.xMin) or (xPosition > bounds.xMax) or (yPosition < bounds.yMin) or (yPosition     > bounds.yMax)

  end

  function object:touch(event)

    local phase = event.phase

    if (phase == “began”) then

      object.startX = object.x

      object.startY = object.y

    elseif (phase == “moved”) then

      object.x = object.startX + event.x - event.xStart

      object.y = object.startY + event.y - event.yStart

    elseif (phase == “ended” or phase == “cancelled”) then

      object:snap(params.xOffset, params.yOffset)

    end

    if (object:hasnot(event.x, event.y)) then

      object:snap(params.xOffset, params.yOffset)

    end

    return true

  end

  object:addEventListener(‘touch’)

[/lua]

Again, it functions well except when my cursor leaves the object during a fast drag. How can I detect this situation?

I would imagine it’s because you haven’t set the focus to the current object.

In your began phase, use 

display.getCurrentStage():setFocus( event.target )

and then setFocus back to nil in the ended/cancel phase

See

https://docs.coronalabs.com/api/library/display/getCurrentStage.html

I would imagine it’s because you haven’t set the focus to the current object.

In your began phase, use 

display.getCurrentStage():setFocus( event.target )

and then setFocus back to nil in the ended/cancel phase

See

https://docs.coronalabs.com/api/library/display/getCurrentStage.html