Hi. I typed up an answer then borked it by clicking the wrong button… so this second post will be a little less verbose. Sorry.
-
Thanks for posting the link. I did not however look and instead going directly to solution.
-
The trick to making this work is proper display group hierarchy and only moving the parent group, not child groups.
-
If you’re having physics issues, you are changing the alignment of groups relative to each other and this is borking you up.
-
Here is ONE way to do it.
Make The Layers
local layers = display.newGroup() layers.world = display.newGroup() layers.under = display.newGroup() layers.content = display.newGroup() layers.over = display.newGroup() – Insert layers into sceneGroup if you’re using composer.* sceneGroup:insert( layers ) layers:insert( layers.world ) layers.world:insert( layers.under ) layers.world:insert( layers.content ) layers.world:insert( layers.over ) – Now you have this BOTTOM TO TOP layering all packaged in – layers which has named fields refering to the groups for easy use – sceneGroup – if using composer – VERY BOTTOM – layers – world (child of layers) – under (child of world) – content (child of world) – over (child of world) – VERY TOP
Add Content In Correct Layers
Never add content to layers.world. This is your camera layer and should only contain the child groups we created.
local player = display.newImageRect( layers.content, ... ) -- add body, etc. local ground = display.newImageRect( layers.under, ... ) local cloud = display.newImageRect( layers.over, ... ) local enemy = display.newImageRect( layers.content, ... ) -- add body, etc. .. more as needed
The Camera Code
You are essentially talking about a camera above. This is a tracking camera.
local function attachCamera( trackObj, world, params ) params = params or {} local lockX = params.lockX local lockY = params.lockY local lx = 0 local ly = 0 lx = params.lx or trackObj.x ly = params.ly or trackObj.y world.enterFrame = function( event ) local dx = 0 local dy = 0 if(not lockX) then dx = trackObj.x - lx end if(not lockY) then dy = trackObj.y - ly end if(dx ~= 0 or dy ~= 0) then world:translate(-dx,-dy) lx = trackObj.x ly = trackObj.y end return false end Runtime:addEventListener( "enterFrame", world ) world.finalize = function( self ) Runtime:removeEventListener( "enterFrame", self ) end world:addEventListener( "finalize" ) end
Start Tracking Player
The function above supports a few options and you can explore them. I’ll show a call that matches your usage as I understand it:
-- \> Attach camera code to world and player and start tracking player -- \> Ignore Y movement, only track horizontal movement. -- \> Player may not be in center of screen, so assume it is not and track it at whatever -- offset it is at. attachCamera( player, layers.world, { lockY = true } )
That is it. This code updates the position of the world group ONLY and thus keeps all the other groups aligned, avoiding the physics problem you are seeing.