Scrolling around a large level

The result of reducing the background to a screen-sized window is that it has to be kept placed behind whatever section of the world is currently visible in that screen.

Getting on with it

Open world.lua, if needed.

Displaying the visible background

Insert a new local function before the module function, which will set the world tiles to display the needed portion of the background:

local function alignBackground(world, ground)
end

return function (terrain, columns, rows)

First, determine which tile appears in the top-left corner of the screen:

local function alignBackground(world, ground)
  local x, y = world:contentToLocal(0, 0)
  x, y = math.floor(x / world.HSize), math.floor(y / world.VSize)
end

Next, go through each of the tiles of the visible background:

  x, y = math.floor(x / world.HSize), math.floor(y / world.VSize)
  for v, row in ipairs(world.Tiles) do
    local sourceRow = world.Map[y + v]
    for h, tile in ipairs(row) do
    end
  end
end

For each one, set it to display the appropriate piece of terrain, based on which tile of the original map would be in that section:

    local sourceRow = world.Map[y + v]
    for h, tile in ipairs(row) do
      local space = sourceRow and sourceRow[x + h]
      if space then
        tile.isVisible = true
        tile:setSequence(space.GroundType)
        tile:play()
      end
    end
  end

If the tile has slipped off the bounds of the map, hide the tile until the map moves back:

      if space then
        tile.isVisible = true
        tile:setSequence(space.GroundType)
        tile:play()
      else
        tile.isVisible = false
      end

Aligning the background with the screen

This keeps the background showing the part of the world that should be on screen, but the background object itself doesn't move within the world as the world scrolls. This, however, can be fixed easily:

        tile.isVisible = false
      end
    end
  end
  ground.x, ground.y = x * world.HSize, y * world.VSize
end

The background snaps to tile boundaries as it is moved about.

Finally, make sure that the function actually gets called whenever the map is updated:

  function self:View(x, y)
    matchPointPlacement(self, x, y, display.getCurrentStage(), display.contentCenterX, display.contentCenterY)
    alignBackground(self, self.Ground)
  end

What did we do?

We created a function that links the visible portions of a world to the slice of the map structure that describes them, and positions the tiles so that they stay in sync with the world as it is being moved.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.79.241