[Resolved] Drag and Collision Event

Hi community,

Here I am again asking for help . What I’m trying to do is have a object being dragged to another object. If it collides during release of the object being dragged it is then put on the same position of the other object and if not, still during release, it goes back to the original position. Here is my code:

physics.start()
physics.setGravity( 0, 0 )
local getpos = false
local xpos = 100
local ypos = 300

local hero = display.newCircle( 40, 40, 30 )
hero.name = “hero”
hero:setFillColor(50, 100, 150)
hero.x = 100; hero.y = 100
physics.addBody(hero, “dynamic”)

local colorSensor = display.newCircle( 160, 240, 80, 0 )
physics.addBody(colorSensor, {isSensor = true})
colorSensor.x = xpos; colorSensor.y = ypos
colorSensor.strokeWidth = 3
colorSensor:setFillColor(100,80, 120,255)
colorSensor:setStrokeColor(255, 255, 255)

local function moveHero (event)
local t = event.target
local phase = event.phase

if “began” == phase then
display.getCurrentStage():setFocus( t )
t.isFocus = true

t.x0 = event.x - t.x
t.y0 = event.y - t.y

elseif t.isFocus then
if “moved” == phase then
t.x = event.x - t.x0
t.y = event.y - t.y0

elseif “ended” == phase or “cancelled” == phase then
if getpos then
t.x = colorSensor.x
t.y = colorSensor.y

else
t.x = xpos
t.y = ypos

end

display.getCurrentStage():setFocus( nil )
t.isFocus = false
end
end
end
hero:addEventListener(“touch”, moveHero)

colorSensor:addEventListener(“collision”, colorSensor)
function colorSensor:collision (event)
if event.other.name == “hero” and event.phase == “began” then
getpos = true
red = math.random(0,255)
green = math.random(0,255)
blue = math.random(0,255)
hero:setFillColor(red, green, blue)

elseif event.phase == “ended” then
print (“ENDED”)
getpos = false
end

end

By the way, the problem is that even if there is no collision the draggable circle still gets the position of the bigger circle. And BTW if ever you try this code the small did not dissappear it is behind the big circle. [import]uid: 141531 topic_id: 25901 reply_id: 325901[/import]

Nevermind I solved it. Being stupid again. Made a mistake in declaring the X and Y of the big circle. the big circle should be in static while the small circle’s X and Y should be the xpos and ypos respectively. [import]uid: 141531 topic_id: 25901 reply_id: 104823[/import]

Hey, well done on solving your problem - I don’t think it’s stupid, we all make mistakes sometimes :slight_smile:

That said, please post your code in < lua > tags in the future. Eg;
< lua >
code goes here
< /lua >

Without the spaces. That makes it readable :wink: [import]uid: 52491 topic_id: 25901 reply_id: 104837[/import]

oh okay thanks. [import]uid: 141531 topic_id: 25901 reply_id: 104848[/import]