Question

I'm trying to create a simple game where the player controls a ship that moves around in the "world". The thing that makes this a little trickier is that I want to rotate the "world" around the ship when it turns, so that the ships front is always facing towards the top of the phone screen.

I've created a group that contains the "world" and the ship as well as a group that I call cameraLayer that "follows" the ship around. All of this works fine in the sense that I can move the ship around and always keep it in the center of the phone screen. However, I can't seem to get the cameraLayer to rotate properly in relation to the ships rotation.

Here's the code for the two groups:

physicsLayer = display.newGroup()
physicsLayer:insert(bg)
physicsLayer:insert(player)

cameraLayer = display.newGroup()
cameraLayer:insert(physicsLayer)
cameraLayer.rotation = 0
cameraLayer.xScale = 1
cameraLayer.yScale = 1
cameraLayer.anchorX = 0.5
cameraLayer.anchorY = 0.5
cameraLayer.x = centerX
cameraLayer.y = centerY
cameraLayer.angle = 0

Here's the move function:

local function move()

    player.x = player.x + Cos( Rad(player.angle) ) * 2
    player.y = player.y + Sin( Rad(player.angle) ) * 2 

    cameraLayer.x = cameraLayer.x - Cos( Rad(cameraLayer.angle) ) * 2
    cameraLayer.y = cameraLayer.y - Sin( Rad(cameraLayer.angle) ) * 2   

end

Here's the rotation function:

local function enterFrameListener(key)
    if holding then
        if leftKey.isFocus == true then
            player.angle = player.angle - 3
            player.rotation = player.rotation - 3

            cameraLayer.angle = cameraLayer.angle - 3
        elseif rightKey.isFocus == true then
            player.angle = player.angle + 3
            player.rotation = player.rotation + 3

            cameraLayer.angle = cameraLayer.angle + 3
        end
    else
        -- Not holding
    end
end

I've tried to research as much as possible, but I've not found anything that could help me resolve my problem. Any form of help would be highly appreciated!

Was it helpful?

Solution

Your last comment jogged my memory - you need to continually adjust the anchor point of the world, so that it rotates around the point where your ship is. I keep the ship above the world and reset the world anchor points with the code below - hopefully this will help! :D

-- position the map in the viewport
function viewport:positionMap( x, y )
    aX = ( mapSize * 0.5 + x ) / mapSize
    aY = ( mapSize * 0.5 + y ) / mapSize
    self.map.anchorX = aX
    self.map.anchorY = aY
end

(The viewport object is a container clipping the world map)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top