Hi, I’m trying to make a game where you swipe up, down, left or right to move a block in that direction, I’ve got all the code right, except for one small problem: In the swipe function, this line of code: timer.performWithDelay(200, eventAdd), gives the user the ability to swipe the block in a different direction while it is still moving, which is something that I don’t want. However, if I comment out this line of code, it causes this problem: If I, for example, swipe up and allow the block to collide with “ceiling” and then try to swipe up again, the block sticks to “ceiling” and I am unable to make any more moves. Please help, any will be greatly appreciated
local composer = require( “composer” )
local scene = composer.newScene()
local physics = require “physics”
physics.start()
physics.setGravity(0,0)
physics.setDrawMode(“normal”)
physics.setVelocityIterations( 100)
physics.setPositionIterations( 100)
local beginX
local beginY
local endX
local endY
local xDistance
local yDistance
local rect = display.newRect(10,10,10,10)
physics.addBody(rect,“dynamic”, {bounce = 0.000})
rect.linearDamping = 0
rect.isBullet = false
rect.isFixedRotation = true
rect.x = 200
rect.y = 210
rect.isAwake = false
rect.isBodyActive = true
rect:setFillColor(0,0,1)
local ceiling = display.newLine(0,0,500,0)
ceiling.y = -45
physics.addBody(ceiling, “static”, {density = 1000, bounce = 0, friction = -100})
local ground = display.newLine(0,0,500,0)
ground.y = 525
physics.addBody(ground, “static”, {density = 1000,bounce = 0, friction = -100})
local leftWall = display.newLine(-1,600,-1,-2000)
physics.addBody(leftWall, “static”, {density = 1000,bounce = 0, friction = -100})
local rightWall = display.newLine(321,600,321,-2000)
physics.addBody(rightWall, “static”, {density = 1000,bounce = 0})
function checkSwipeDirection()
xDistance = math.abs(endX - beginX)
yDistance = math.abs(endY - beginY)
if xDistance > yDistance then
if beginX > endX then
print(“swipe left”)
rect:setLinearVelocity(-600,0)
else
print(“swipe right”)
rect:setLinearVelocity(600,0)
end
else
if beginY > endY then
print(“swipe up”)
rect:setLinearVelocity(0,-600)
else
print(“swipe down”)
rect:setLinearVelocity(0,600)
end
end
end
function eventAdd()
Runtime:addEventListener(“touch”, swipe)
end
function eventRemove()
Runtime:removeEventListener(“touch”, swipe)
end
function swipe(event)
if event.phase == “began” then
beginX = event.x
beginY = event.y
end
if event.phase == “ended” then
endX = event.x
endY = event.y
checkSwipeDirection();
Runtime:removeEventListener(“touch”, swipe)
timer.performWithDelay(200, eventAdd) – this removes the problem of
– stick, however it allows
– the blocks to move at any point
– in time
end
end
function onCollision( event )
if ( event.phase == “began” ) then
timer.performWithDelay(200, eventAdd)
end
end
if rect.isAwake == false then
Runtime:addEventListener(“touch”, swipe)
end
Runtime:addEventListener(“collision”, onCollision)