this isn’t perfect but shows 8 way tile scrolling. click the edges of the screen to scroll in that direction.
there is an extra row and an extra column outside the screen to allow for scrolling 32 pixels before redrawing the tiles
ie this is moving 11x16 tiles around that are 32x32px in size. it’s using the equivalent of Flash gotoAndStop method.
get tileset.png from here:
http://love2d.org/w/images/b/b5/Resource-ExampleEfficientTileset.png
[lua]require(“sprite”)
local map – stores tiledata
local mapWidth, mapHeight – width and height in tiles
local mapX, mapY – view x,y in tiles. can be a fractional value like 3.25.
local oldMapX, oldMapY
local tilesDisplayWidth, tilesDisplayHeight – number of tiles to show
local tilesetImage
local tileSize = 32 – size of tiles in pixels
local tilesetSprite
local moveX = 0
local moveY = 0
local moveAmount=1/32 – in tile units, so to move 1px at a time set moveAmount to 1/tileSize
function load()
setupMap()
setupMapView()
setupTileset()
end
function setupMap()
mapWidth = 60
mapHeight = 40
local i=1
map = {}
for x=1,mapWidth do
map[x] = {}
for y=1,mapHeight do
– pick a random tile for now
map[x][y] = math.random(1,70)
i=i+1
end
end
end
function setupMapView()
mapX = 1
mapY = 1
tilesDisplayWidth = 11 --(10 * 32 = 320, plus 1 spare column)
tilesDisplayHeight = 16 --(15 * 32 = 480, plus 1 spare row)
end
function setupTileset()
spritemap = display.newGroup()
spriteSheet = sprite.newSpriteSheet(“tileset.png”, tileSize, tileSize)
spriteSet1 = sprite.newSpriteSet(spriteSheet, 1,100)
for x=1,tilesDisplayWidth,1 do
for y=1,tilesDisplayHeight,1 do
local tilesprite = sprite.newSprite( spriteSet1 )
tilesprite.x = (x-1)*tileSize+(tileSize/2)
tilesprite.y = (y-1)*tileSize+(tileSize/2)
spritemap:insert(tilesprite)
end
end
updateTilesetBatch()
end
function updateTilesetBatch()
local i = 1
for x=1, tilesDisplayWidth,1 do
for y=1, tilesDisplayHeight, 1 do
spritemap[i].currentFrame = map[x+math.floor(mapX)][y+math.floor(mapY)]
i = i + 1
end
end
end
– central function for moving the map
function moveMap(dx, dy)
oldMapX = mapX
oldMapY = mapY
mapX = math.max(math.min(mapX + dx, mapWidth - tilesDisplayWidth), 1)
mapY = math.max(math.min(mapY + dy, mapHeight - tilesDisplayHeight), 1)
spritemap.x = 0-((mapX * tileSize)%tileSize)
spritemap.y = 0-((mapY * tileSize)%tileSize)
if math.floor(mapX) ~= math.floor(oldMapX) or math.floor(mapY) ~= math.floor(oldMapY) then
updateTilesetBatch()
end
end
function update(event)
– if move amount is set, move the map
if(moveX~=0 or moveY~=0) then
moveMap(moveX,moveY)
end
end
function onTap(event)
– tap edges of screen to move
if(event.x < 100) then
moveX=-moveAmount
elseif(event.x > 220) then
moveX=moveAmount
else
moveX=0
end
if(event.y < 100) then moveY=-moveAmount
elseif(event.y > 380) then moveY=moveAmount
else moveY=0
end
end
load()
Runtime:addEventListener(“enterFrame”,update)
Runtime:addEventListener(“tap”, onTap)[/lua] [import]uid: 6645 topic_id: 3534 reply_id: 10825[/import]