Tile Scrolling with Maps Made with my Map Editor

Little tutorial on scrolling a map/world made with my Map Editor.

First, the source code in full:

Import mojo2
Import brl

Function Main()
	New MyApp
End

Class MyApp Extends App

	Field canvas:Canvas
	Field gfxShapes:Image
	Field touchX,touchY:Float
	Field prevTX,prevTY:Float
	Field scaleX,scaleY:Float
	Field scrollX,scrollY:Float
	Field touchXD,touchYD:Float
	Field scroll:Bool
	Field map:Int[]
	Field worldHeight:Int, worldWidth:Int	
	
	Field mapX:Int
	Field mapY:Int
	
	Method OnCreate()
		canvas = New Canvas()
		

		gfxShapes = Image.Load("shapes.png")

		SetDeviceWindow(640,480,0)
		scaleX = DeviceWidth() / 640.0
		scaleY = DeviceHeight() / 480.0
		
		Local mapFile:=FileStream.Open("cerberus://data/map.dat","r")

		worldWidth = mapFile.ReadInt()
		worldHeight = mapFile.ReadInt()
		
		map = map.Resize(worldWidth * worldHeight)
		
		For Local i:Int = 0 To worldWidth * worldHeight - 1
			map[i] = mapFile.ReadInt()
		Next
			
		mapFile.Close()
		
		mapX = 0
		mapY = 0
		
	End
	
	Method OnUpdate()

		touchX = TouchX()
		touchY = TouchY()
										
		If TouchDown(0) > 0 Then
			
			scrollX = (touchX - prevTX)
			scrollY = (touchY - prevTY)
 			
			If Abs(scrollX) > Abs(scrollY) Then
				If scrollX < 0 Then mapX = mapX - 1 Else mapX = mapX + 1
			Else
				If scrollY < 0 Then mapY = mapY - 1 Else mapY = mapY + 1
			Endif
			
			If mapX < 0 Then mapX = 0
			If mapX > worldWidth - 40 - 1 Then mapX = worldWidth - 40 - 1
			If mapY < 0 Then mapY = 0
			If mapY > worldHeight - 30 - 1 Then mapY = worldHeight - 30 - 1

		Endif

		prevTX = touchX
		prevTY = touchY	

	End

	Method OnRender()
		canvas.PushMatrix()
		canvas.Scale(scaleX,scaleY)
		
		For Local y:Int = 0 To 30 - 1
			For Local x:Int = 0 To 40 - 1
				canvas.DrawRect(x * 16, y * 16, gfxShapes, 0, map[mapX + x + (mapY + y) * worldWidth] * 16, 16, 16)
			Next
		Next

		canvas.Flush()
		canvas.PopMatrix()
	End
	
End Class

Quite straight forward, but some words about the code.

In the Map Editor dat-file, the first 4 byte integer declares the width of the map, the second the height of the map in tiles. The size of the map is read first, then the map itself.

The scrolling is made with touch screen in mind.

The meaning of the Abs(…)-sentence is, that in which direction in the touch screen the finger is being moved most and then the map is scrolled into that direction.

The 256 color shapes of the world are from an Ultima IV remake and are free to be used. The original project is “xu4”, if my memory servers me right.

The source above is places to public domain as license for it.

Please, if you make a game (in any programming language) utilizing my code, show me, what you have achieved. I’m big fan of games of this kind of genre.

 

For the end a video regarding this post. At the beginning of the video there’s some scrolling: