Hi. I want to add collision as well as make the randomly displayed objects dragable.The objects fall from the top.Here’s how I tried but not working.I haven’t added code to drag randomly displayed objects here but I have tried.Only objects are being displayed.Help me with this issue.Thanks.
local function box()
rand = math.random( 10 )
if (rand < 5) then
local crate1 = display.newImageRect( “but3.jpg”, 100, 100 )
crate1.x, crate1.y = 53, -80
physics.addBody( crate1, { density=0, friction=0.3, bounce=0 } )
physics.setGravity( 0, 1)
crate1.myName = “crate1”
local crate3 = display.newImageRect( “crate.png”, 100, 100 );
crate3.x, crate3.y = 267, -80
physics.addBody( crate3, { density=0, friction=0, bounce=0 } )
physics.setGravity( 0, 1)
elseif(rand < 9 ) then
local crate1 = display.newImageRect( “but3.jpg”, 100, 100 );
crate1.x, crate1.y = 53, -80
physics.addBody( crate1, { density=0, friction=0.3, bounce=0 } )
physics.setGravity( 0, 1)
crate1.myName = “crate1”
local crate2 = display.newImageRect( “crate.png”, 100, 100 );
crate2.x, crate2.y = 160, -80
physics.addBody( crate2, { density=0, friction=0.3, bounce=0 } )
physics.setGravity( 0, 1)
else
local crate2 = display.newImageRect( “crate.png”, 100, 100 );
crate2.x, crate2.y = 160, -80
physics.addBody( crate2, { density=0, friction=0.3, bounce=0 } )
physics.setGravity( 0, 1)
local crate3 = display.newImageRect( “crate.png”, 100, 100 );
crate3.x, crate3.y = 267, -80
physics.addBody( crate3, { density=0, friction=0, bounce=0 } )
physics.setGravity( 0, 1)
end
end
local function gameLoop()
box()
end
gameLoopTimer = timer.performWithDelay( 3000, gameLoop, 0 )
local platform = display.newRect( 0, 0, 60, 30 )
platform.surfaceType = “superbounce”
platform.x, platform.y = display.contentCenterX, display.contentCenterY+80
physics.addBody( platform, “static”, { bounce=0.0, friction=0.3 } )
platform.myName = “platform”
–Code to drag Platform
local function dragplatform( event )
local platform = event.target
local phase = event.phase
if ( “began” == phase ) then
– Set touch focus on the platform
display.currentStage:setFocus( platform )
– Store initial offset position
platform.touchOffsetX = event.x - platform.x
platform.touchOffsetY = event.y - platform.y
elseif ( “moved” == phase ) then
– Move the platform to the new touch position
platform.x = event.x - platform.touchOffsetX
platform.y = event.y - platform.touchOffsetY
elseif ( “ended” == phase or “cancelled” == phase ) then
– Release touch focus on the platform
display.currentStage:setFocus( nil )
end
return true – Prevents touch propagation to underlying objects
end
platform:addEventListener( “touch”, dragplatform )
–HERE IS THE CODE FOR COLLISION.
local function onCollision( event )
if ( event.phase == “began” ) then
local obj1 = event.object1
local obj2 = event.object2
if ( obj1.myName == “platform” and obj2.myName == “crate1” )
then
display.remove( obj1 )
end
end
