Gideros Mobile Tutorial 7: Classes & Inheritance

So far we put all the code in one file. In previous example if we wanted to add more balls we would have to add several lines of  code for every ball we add – like creating new bitmap, setting new position, anchor etc. Even the functions are written in a way that they call “ball” methods directly. How to avoid this and make it more universal, more reusable?

Classes &  Instances

I will not go into details about Lua language but in short, Lua does not support classes the way that languages like C++, Java and ActionScript do. It has roots from prototype-based languages. In Lua, each object can define its own behavior through metatables so in a way we emulate OO programming and classes in Lua.

Creating instances is easy through a new function:

local sprite = Sprite.new()
local texture = Texture.new("image.png")
local bitmap = Bitmap.new(texture)
local timer = Timer.new(1000, 0)

Inheritance

It is through the inheritance that we can “emulate” the classes just like in other languages – they will have variables, methods etc. Then we put these classes into their own files and Gideros will load them automatically. We use the Core.class function to create our own classes through inheritance. We can inherit from Sprite, EventDispatcher and so on. Keyword self is the equivalent of the this pointer in C++ and it is a reference to the table which is created as part of the Class.new() command.

Here is a simple inheritance example:

Player = Core.class(Sprite) -- we create our own player class, inherited from the Gideros Sprite core class

--init() function is called automatically when we create(instantiate) new Player
-- it is like a constructor function
function Player:init()
-- do the initialization of Player instance,we set custom variables
self.health = 100
self.speed = 3
end

function Player:walk()
-- this is a Walk method of a Player class
	print("Player Walking - health:", self.health)
end

function Player:jump()
-- jump logic
end

newPlayer = Player.new() --create new Player instance
anotherPlayer = Player.new() --another Player instance
--we add both to stage
stage:addChild(newPlayer)
stage:addChild(anotherPlayer)

print (newPlayer.health)

--we call their methods
newPlayer:walk()
newPlayer.health = 50
anotherPlayer:walk()

As you can see, in the and it looks similar to OO in other languages. In above example we put all the code in main.lua but we could take all the (class,methods..) code (line 1-18) and put it in player.lua file and the rest we would leave in main.lua. This is what we will do in next example.

Now lets take the code from previous tutorial and turn it into what we learned today. First you create a ball.lua file. The code is pretty much copy/paste from or previous ball example except that we access variables and methods with self (it is also used instead of word ball). As you will see we use word self. I understand that we access class variables and class methods with self word but I am not so sure why we need to pass another self to self:addEventListener function (if you know let me know in comments, I am still learning). This self word is use everywhere so it can be quite confusing for beginners.

Put this in ball.lua (Code is commented):

-- create our own Ball class

Ball = Core.class(Sprite)

--init will run every time we create new Ball object (Ball.new)
function Ball:init (texture) --we will pass texture name
	self.direction = 3
	local bitmap = Bitmap.new(Texture.new(texture,true))
	self:setPosition(math.random(0, 270),math.random(0, 430)) --put ball on random position on screen
	bitmap:setAnchorPoint(0.5,0.5)
	self:addChild(bitmap)
	self:addEventListener(Event.ENTER_FRAME, self.rotateBall,self)
	self:addEventListener(Event.MOUSE_DOWN, self.changeBallDirection,self)
	self:addEventListener(Event.MOUSE_UP, self.fallDown,self)
	self:addEventListener(Event.MOUSE_MOVE, self.moveBall,self)
end

-- function rotating ball - executed every frame
function Ball:rotateBall()
self:setRotation(self:getRotation()+self.direction)
end

-- function scale ball - executed every mouse press
-- it is not actually mouse,it means no multi touch
function Ball:changeBallDirection(event)
	if self:hitTestPoint(event.x, event.y) then
		-- zoom the ball - jump up
		GTween.new(self, 0.3, {scaleX = 2, scaleY = 2}, {ease = easing.linear})
		soundJump:play()
		self.direction = math.random(-20,20) --random rotation speed(left or right)
	end
end

function Ball:fallDown(event)
	if self:hitTestPoint(event.x, event.y) then
		-- zoom the ball - jump up
		GTween.new(self, 1.5, {scaleX = 1, scaleY = 1}, {ease = easing.outBounce})
		soundBounce:play()
	end
end

--move the ball
function Ball:moveBall(event)

	if self:hitTestPoint(event.x, event.y) then
		local dx = event.x - self:getX()
		local dy = event.y - self:getY()

		self:setX(self:getX() + dx)
		self:setY(self:getY() + dy)
		self.x0 = event.x
		self.y0 = event.y

	 --not sure why this is here, maybe once we start moving ball
         -- we don't need to check if the ball is moved?
           event:stopPropagation()
	end
end

Gideros will automatically load and run this file when you run the program. Now create main.lua, it will be much shorter and you will see how easy is to create new balls:

-- you can apply some settings to your entire application
application:setKeepAwake(true)
application:setScaleMode("letterbox") --proper "full screen" scaling for most devices

-- global direction variable,rotate counterclockwise -3
--direction = 3

-- load background image
local field = Bitmap.new(Texture.new("gfx/field.png",true))

-- load sound that will be played when we press on ball
soundJump = Sound.new("snd/jump.mp3")
soundBounce = Sound.new("snd/bounce.mp3")

-- here we create new ball instances,we pass texture name as argument
-- Ball.new will create objects that we defines in ball.lua
--ball2.png and ball3.png are just different balls - try using your own images
newBall = Ball.new("gfx/ball5.png")
newBall2 = Ball.new("gfx/ball2.png")
newBall3 = Ball.new("gfx/ball3.png")

--add field for background and all balls to stage
stage:addChild(field)
stage:addChild(newBall)
stage:addChild(newBall2)
stage:addChild(newBall3)

and that’s it. You can see it is much clearer this way and we only need to create new Ball objects and you will have new ball with all the methods and all. Try to add new balls and you will see them appearing on the screen and each ball can be picked up, dragged etc. You can create of course a lot of classes like this, for every object you want. If you had a football(soccer) game then we have the ball class already. Then you would for example create player.lua and put all logic for all players there – they all behave in similar way. You could create a goalie.lua and referee.lua class/file for goal keeper and referee if you want because they behave differently and have different logic than players (or you could use different methods in player.lua class, as you wish). If you had an active audience you can create audience.lua class etc. You don’t need to create these classes just for objects – you can also create it for example to handle all the audio effects in the game and so on.

Passing arguments to functions

We are currently just passing a texture file name to Ball class init() method and then randomly setting x and y but you can of course change this and pass x and y .

So in ball.lua you need to modify function init (I am only showing lines that need to be changed):

function Ball:init (texture,x,y) --2 new arguments
        --everything stays the same except 
        self:setPosition(x,y) --explicitly set x and y
        --everything else is the same
end

and now we also change few lines in main.lua:

newBall = Ball.new("gfx/ball5.png",10,200)
newBall2 = Ball.new("gfx/ball2.png",200,40)
newBall3 = Ball.new("gfx/ball3.png",150,300)

This way you can create new ball at any position you wan’t. You can of course pass other arguments ,as many as you wan’t.

Gideros Mobile Tutorial 5: Events

So far we only displayed some graphics on the screen, we even animated (not real animation though, just rotation of one bitmap) it but there was no user interaction at all. We had one event in Tutorial 4 but it was not really explained in details what it does.

Events and addEventListener

With events we handle responses and they allow us to create interactive applications. The target of an event is a listener function and an optional data value so when an event is dispatched, the registered function is called.  If the optional data value is given, it is used as a first parameter while calling the listener function.  In Gideros we have built-in events generated by the system (e.g. ENTER_FRAME event, touch events, timer events, etc.) and custom events which can be generated by the user.

Here are few examples of kinds of events:

  • ENTER_FRAME  – this event is dispatched every frame. If your game is 60 fps then 60 times/s
  • MOUSE_DOWN – dispatched every time someone presses “mouse” button
  • MOUSE_UP – dispatched every time “mouse” button is released
  • TOUCHES_BEGIN – dispatched every time screen is touched
  • TIMER  – events tied to timers

Just to make it less confusing: We don’t actually use mouse on smartphones of course so you can use MOUSE_ events to handle only a single touch on specific object. In case you want to handle multi touch then you should use TOUCHES_ events because they will provide you with more information about current touch id and all available touches on the screen.

Here is a quick example of an event and function it calls. Let’s suppose we already loaded bitmap ball.

-- function that will be called every time event is dispatched
function rotateBall(event)
 --some code to rotate the ball
end
-- we attach event to ball's addEventListener
ball:addEventListener(Event.ENTER_FRAME, rotateBall)

So basically what this means is we attached addEventListener to our ball object and what it will do is it will call function rotateBall on every frame change. If we would have Event.MOUSE_DOWN instead then rotateBall function would be called every time we press/touch the ball.

At the end of this tutorial we will have a rotating ball that will randomly change direction, rotation speed and play a sound every time you press it.  In next tutorial (tutorial 6) we will add some events that will make the ball dragable and the effects of picking up and dropping the it.

Ok, enough of theory, let’s build an app (with graphics and sound effects). Create project “Events” and add main.lua.

Note: So far we put all the files in one folder but as the app grows larger it is better to be organized. So we will put graphics in gfx  folder and sounds in snd  folder. I prepared a file for you so download it and extract it to your project folder. Important: Gideros project folder  structure is independent of your OS folder structure so you will have to create folder in Gideros by yourself and add existing files there. In theory this means that you might have all the files in one folder on disk but in Gideros they are nicely structured – or the opposite of course!

Add this code to main.lua :

-- you can apply some settings to your entire application
application:setKeepAwake(true) 
application:setScaleMode("letterbox") --proper "full screen" scaling for most devices

-- global direction variable,rotate clockwise 3
direction = 3

-- load the textures and create bitmap objects
--2nd texture parameter can be set to true to get anti-aliasing
local field = Bitmap.new(Texture.new("gfx/field.png",true))
local ball = Bitmap.new(Texture.new("gfx/ball5.png",true))

-- load sound that will be played when we press on ball
local soundJump = Sound.new("snd/jump.mp3")

-- set the anchor point in the center of ball it rotates around center
ball:setPosition(120,150)
ball:setAnchorPoint(0.5,0.5)

-- function changeBallDirection - executed every frame
function rotateBall(event)
	ball:setRotation(ball:getRotation()+direction)
end

-- function changeBallDirection - executed every mouse press
-- it is not actualy mouse, it means no multi touch
function changeBallDirection(event)
		soundJump:play()
		direction = math.random(-20,20) --random rotation speed(left or right)
end

-- rotateBall function will be called on every frame change
ball:addEventListener(Event.ENTER_FRAME, rotateBall)
-- when we click on the ball it will (or not) change direction
ball:addEventListener(Event.MOUSE_DOWN, changeBallDirection)
-- when we move the mouse then ball also moves

stage:addChild(field)
stage:addChild(ball)

Run it and you will have a nice rotating ball on the field. Now press the ball and it will randomly change the rotation direction and speed, not to mention it will play a sound every time you press it. If you do it long enough you might even make the ball stop rotating (speed=0) 😉

But what a minute – the ball changes rotation/speed even if we click anywhere on the screen! That is not very useful. No worries though, it is easy to fix this,we just need to wrap the reaction between 2 lines. Replace the changeBallDirection function with this:

function changeBallDirection(event)
	if ball:hitTestPoint(event.x, event.y) then
		soundJump:play()
		direction = math.random(-20,20) --random rotation speed(left or right)
	end
end

So we just wrapped the code with hitTestPoint function (lines 2 and 5). This hitTestPoint function simply checks if the given coordinates are in bounds of the sprite/object. Run it and now it only works if you “click” on the ball.

I don’t want to make this tutorial too long and hard to comprehend so we will add some additional events in the next tutorial.

Gideros Mobile Tutorial 3: Shapes

It’s nice to have something else on the screen than just text. Let’s try to draw some shapes. I will leave out step-by-step explanation on how to add files to projects, how to start Gideros Player etc because this was covered in previous tutorials.

Drawing Shapes

You can draw primitive shapes with Gideros on the screen.  Create new project, name it “Shapes”, add new main.lua file and open it in editor.

Remember that in Gideros we create every new object (sprites,textfield,shape,bitmap…) with the keyword new. Add this code (comments — are in the code) to main.lua, run the player and you will see black line on your screen.

local myShape = Shape.new() -- create the shape object assigned to variable myShape
myShape:beginPath()         -- We have to tell shape to begin a path
myShape:setLineStyle(1)     -- set the line width = 1
myShape:moveTo(100,100)     -- move pen to start of line
myShape:lineTo(200,100)     -- draw line to new coordinates
myShape:endPath()           -- end the path
stage:addChild(myShape )    -- add the shape to the stage - display it

I think it is not hard to see what is going on here. We can use pen & paper analogy to explain it even simpler: The “moveTo” function is like lifting a pen off the paper and moving it to a different location without drawing anything. The “lineTo” function draws a straight line from current pen location to the destination location. As you can see once we create new Shape object named myShape we always use “myShape:” to change it’s properties, do something with it etc.

I am sure developers understand the screen coordinate system (line from 100,100 to 200,100) but here is the coordinate system just in case:
coordinates

Fun with Shapes

Now let’s draw a rectangle, fill it will color and apply some transformations learned in previous lessons. Shapes are “anchored” at the graph origin (0,0). The anchor point affects how the shape behaves when manipulated (e.g., rotated, scaled). If we want to prevent out rectangle from previous example to move off the screen we first create the shape at 0,0 coordinates (left top corner) and then move it to 100,100.

Modify the code so it will look like this:

local myShape = Shape.new() -- create the shape object assigned to variable myShape
myShape:beginPath()         -- We have to tell shape to begin a path
myShape:setLineStyle(2)     -- set the line width = 2
myShape:setFillStyle(Shape.SOLID, 0xFF0000) -- solid red fill color
myShape:moveTo(0,0)     -- move pen to start of line
myShape:lineTo(100,0)     -- draw top of rectangle
myShape:lineTo(100,100)     -- draw right side of rectangle
myShape:lineTo(0,100)     -- draw bottom of rectangle
myShape:lineTo(0,0)     -- draw left side of rectangle
myShape:endPath()           -- end the path
-- now we apply some transformations to the shape we created
myShape:setPosition(100,100) -- move the entire shape to 100,100
myShape:setScale(1.2,1.5) -- scale x by 1.2 and y by 1.5. The shape wont be rectangle anymore
myShape:setRotation(40) -- rotate shape by 40 degrees
stage:addChild(myShape )     -- add the shape to the stage - display it

Play with it a little, create different shapes.

Gideros Mobile Tutorial 2: “Hello World”

Hello World

Every tutorial starts with “Hello World” and who am I to break this tradition? :) Please keep in mind that I will not be teaching Lua language, concepts of Objects, functions etc.  I am assuming that you are a developer who knows at least one language and have a basic understanding of how programing works. Again, I am just learning Lua too so you don’t need to be master Lua to follow this tutorial.

We will create 2 versions of “Hello World”  – one that prints to console and one that prints to your mobile device phone screen (or Gideros Player).

Hello World on console

Start Gideros(Gideros Mobile Studio) and select File->New Project from menu.  Name the project HelloWorld and browse to directory where you want to store your projects and click OK.  Right click on the HelloWorld project icon and select Add New File as seen below:

gideros_add_new_file

name it main.lua and click ok. This is how you will add new code files to your project. Double click it so it opens in the editor.

Now add just one line:

 print "Hello World!"
 

That is all you need.

Start the the local player (Player->Start Local Player) and press play button on Gideros menu. Program will execute and… nothing will happen on Player. But check the Output window and you will see something like this:

main.lua is uploading.
Uploading finished.
Hello World!

There is our hello world! Of course this is handy when we need to debut or test something but what we want is this text to appear on Player or our smartphone.

“Hello World” on Gideros Player / Smartphone

This takes few more lines but it is still easy. Delete the code in our editor and add this :

-- HelloWorld.lua script
local myTextField = TextField.new(nil, "Hello World!")
myTextField:setPosition(40,100)
stage:addChild(myTextField)

Save it, run Player and you will see text “Hello World” displayed there or on your smartphone (you have to run the Gideros app on your smartphone first of course). Great, your first mobile app is finished!

Let me explain this line by line

-- HelloWorld.lua script 

This is a comment so we can ignore it. In Lua you start one line comments with --. Please check some Lua tutorials on net for more.

local myTextField = TextField.new(nil, "Hello World!")

What we do here is create new text field object with the text Hello World!. Word nil just means that Gideros will use the default font. We assign this to local variable myTextField.

myTextField:setPosition(40,100)

Our myTextField is now TextField object so we can access and use/set all kinds of methods, events and properties. In this case we simply set the position of our textfield to appear on screen (X=40, Y=100).

stage:addChild(myTextField)

In all our previous lines we just created textfield, set its parameters but we have to display it on our screen. Think of stage as screen for now so everything that we want to display will have to be added to stage as its “child”.

Fun with text

Now let’s have some fun with text. Download this font from 1001freefonts.com and extract it to your HelloWorld project folder. Right click on the HelloWorld project icon and select Add Existing Files.. and select the “orange juice 2.0” font.

Now replace/modify your code so it will look like this(comments in the code):

-- HelloWorld.lua script
-- We define the font we will use and set the size to 48
local myfont = TTFont.new("orange juice 2.0.ttf", 48)

-- create 2 text fields with text "Hello World!" and "How are you?" which use myfont
local myTextField = TextField.new(myfont, "Hello World!")
local oneMoreTextField = TextField.new(myfont, "How are you?")

--for myTextField we only set the position of the text on screen
myTextField:setPosition(10,50)

-- for oneMoreTextField we set all kinds of properties - position, color (in HEX), rotation.. 
oneMoreTextField:setPosition(40,100)
oneMoreTextField:setRotation(31)
oneMoreTextField:setTextColor(0xFF0000)

-- add both to stage(screen) so we can see them
stage:addChild(myTextField)
stage:addChild(oneMoreTextField)

This is what you should see if you did everything right. Cool! hello_world_fun