Here is some quick code to show you how to do it. This is not the be all and end all solution, feel free to modify to suit your needs, or improve upon it.
Dump this in a main.lua and supply a background image, and an image for the enemy object and have a play. There is a strange hitch in the movement of the object that I didn’t have time to debug. It still functions properly, but you will notice the hitch. Even with the hitch, the principle is sound.
Hope it helps.
[lua]–I wrote the code to display on the iPad in the simulator, so background image is 768 x 1024
–and enemy is an image of 36x32
– I commented to help explain what is going on
_W = display.contentWidth; _H = display.contentHeight; – globals for the screen width and height
local deltaX, deltaY; --forward declarations
local background = display.newImage(“background.jpg”, 0,0);
background.x = _W*0.5; background.y = _H*0.5;
local enemy = display.newImage(“Alien.png”, 0, 0);
enemy.x = _W*0.5; enemy.y = _H*0.5;
local function touchAndMove(event) – touch event listener for the background
– here we calculate the delta (difference) between where the user touches, and where the enemy image is on screen.
–We subtract the touches x and y position from the enemies x and y position.
local function calculateDelta()
deltaX = enemy.x - event.x;
deltaY = enemy.y - event.y;
end
–this function moves the object around by moving it to the location of the touches x and y, plus the delta
local function moveObject()
enemy.x = event.x + deltaX;
enemy.y = event.y + deltaY;
end
if(event.phase == “moved”) then
Runtime:addEventListener(“enterFrame”, moveObject);
end
if(event.phase == “began”) then
calculateDelta();
end
if(event.phase == “ended”) then
Runtime:removeEventListener(“enterFrame”, moveObject);
end
end
background:addEventListener( “touch”, touchAndMove )[/lua] [import]uid: 5317 topic_id: 18029 reply_id: 69837[/import]