I am making a game that involves moving a player (.png image) using four buttons: up, down, left, and right. Each button works, but when the user presses anywhere on the screen the player will only be moved in the direction of the first button that was pressed.
Here are two examples:
If I touch the up button, the player image moves up once. Then if I press the left button, the player image moves up once again.
If I first touch the left button, the player image moves left once Then if I press the up button, the player image moves left once again.
Here’s my current code involving moving the player image:
local function move(marker)
if(marker == 1) then
player.y = player.y - tile
elseif marker == 2 then
player.y = player.y + tile
elseif marker == 3 then
player.x = player.x - tile
elseif marker == 4 then
player.x = player.x + tile
end
end
local function makeMoveButtons()
local buttonImages = {{
“up.png”,
tile * 2,
_H - (tile * 5),
}, {
“down.png”,
tile * 2,
_H - (tile * 2)
}, {
“left.png”,
_W - (tile * 3.5),
_H - (tile * 3.5)
}, {
“right.png”,
_W - (tile / 2),
_H - (tile * 3.5)
}
}
buttons = display.newGroup()
for i = 1, #buttonImages do
local button = display.newImage(buttonImages[i][1])
button.width = tile * 2
button.height = tile * 2
button.x = buttonImages[i][2]
button.y = buttonImages[i][3]
function button:touch(event)
if event.phase == “began” then
display.getCurrentStage():setFocus(self, event.id)
self.isFocus = true
return true
elseif event.phase == “moved” then
self.isFocus = false
return true
elseif self.isFocus == true then
if event.phase == “ended” then
move(i)
end
return true
end
end
buttons:insert(button)
buttons[i]:addEventListener(“touch”)
end
end
Any ideas on what’s going on?