Ok I have it working almost how I wanted. However the accuracy of the overlapping isnt quite there yet. Are there any improvements I could make to this code to achieve almost zero overlapping when the user lets go.
[lua]local physics = require “physics”
physics.start()
physics.setGravity(0,10)
physics.setDrawMode(“hybrid”)
local arguments =
{
{ x=50, y=10, w=100, h=100, r=10, red=255, green=0, blue=128 },
{ x=50, y=150, w=100, h=100, r=10, red=0, green=128, blue=255 },
{ x=50, y=300, w=100, h=100, r=10, red=255, green=255, blue=0 }
}
local function onLocalCollision( self, event )
if ( event.phase == “began” ) then
self.isPositionLegal = false
print(“began”)
elseif ( event.phase == “ended” ) then
self.isPositionLegal = true
print(“ended”)
end
end
local function onTouch( event )
local t = event.target
local phase = event.phase
if “began” == phase then
– Make target the top-most object
local parent = t.parent
parent:insert( t )
display.getCurrentStage():setFocus( t )
– Spurious events can be sent to the target, e.g. the user presses
– elsewhere on the screen and then moves the finger over the target.
– To prevent this, we add this flag. Only when it’s true will “move”
– events be sent to the target.
t.isFocus = true
– Store initial position
t.x0 = event.x - t.x
t.y0 = event.y - t.y
elseif t.isFocus then
if “moved” == phase then
t.isSensor = true
t.bodyType = “dynamic”
– Make object move (we subtract t.x0,t.y0 so that moves are
– relative to initial grab point, rather than object “snapping”).
t.x = event.x - t.x0
t.y = event.y - t.y0
if(t.isPositionLegal) then
t.validX = t.x
t.validY = t.y
t:setFillColor(0,255,0)
else
t:setFillColor(255,0,0)
end
elseif “ended” == phase or “cancelled” == phase then
t.bodyType = “kinematic”
t.isSensor = false
t:setFillColor(0,255,0)
t.x = t.validX
t.y = t.validY
display.getCurrentStage():setFocus( nil )
t.isFocus = false
end
end
– Important to return true. This tells the system that the event
– should not be propagated to listeners of any objects underneath.
return true
end
– Iterate through arguments array and create rounded rects (vector objects) for each item
for _,item in ipairs( arguments ) do
local button = display.newRoundedRect( item.x, item.y, item.w, item.h, item.r )
button.isPositionLegal = true
button.validX = item.x
button.validY = item.y
button:setFillColor( item.red, item.green, item.blue )
button.strokeWidth = 6
button:setStrokeColor( 200,200,200,255 )
physics.addBody(button, “kinematic”)
button.linearDamping = 100
button:addEventListener( “touch”, onTouch )
button.collision = onLocalCollision
button:addEventListener(“collision”, button)
end[/lua] [import]uid: 9484 topic_id: 18230 reply_id: 69793[/import]