Spritesomething – iPad/iPhone app

Here’s a great app for drawing pixel art on your iPhone/iPod and iPad.

http://terriblegames.com/spriteSomething/

I highly recommend this. I have been playing with it for hours the last few weeks. It’s really fun and easy to use. It includes a lot o great features for making games. Draw anywhere you have iPhone/iPod and or iPad, at the cafe on the train or on the bus. Draw a quick icon of a beer bottle or martini glass at the pub with your drink as a model! Draw a quick pixel art portrait of your favorite bartender with one hand and your *drink in the other. (I don’t recommend drawing while under the influence of drugs or alcohol. All references to drinks in this article are fruit juice only.)

 

Corona – Widget – Buttons

Buttons are common, every app will use them. They can be as simple as a shape or image that you tap, which is simple to program. For best user experience buttons should change their look when they are tapped, this effect requires more programming. Luckily Corona’s widget library provides an easy to use full featured button. The widget library makes it easy to create a button with interactive features.

The widget.newButton() method creates a button. The default look of the button is determined by the widget theme. Alternately widget also allows you to use images or even a sprite sheet to create buttons.

The button has two states default and over. The default state is what the button looks like with no interaction. The over state is what the button will look like when your finger is in contact with the button. Note the over state on touch devices will usually be mostly hidden beneath your finger. There is no hover state on touch devices which makes it important to design buttons that invite user interaction.

The look of the button is set by the widget theme. You can also use an image or a sprite sheet instead.

The button widget has a label. You can set the font and font size for the label. You can also set the color of the label in both the default and over state. You can use the label with images and sprite sheet, or have no label in the case where the label might be incorporated into an image.

The first step to use the “widget” module is to include it in your project with:

local widget = require( "widget" )

Next create a button using widget.newButton( options ). Options is a table containing properties and values describing the button you are going to make.

For example the following would create a button 160 pixels wide, 40 pixels tall, the label would say “Tap”. A tap and release would be handled by the function on_button.

local button = widget.newButton( {
label="Tap",
width=160,
 height=40,
 onRelease=on_button
 } )

This button would call the on_button function when it is tapped. You might define this event handler in this way:

 

local function on_button()
 print("Button Released")
end

Remember you’d need to define the handler above button definition. All three pieces together might look like this:

local widget = require "widget"

local function on_button(event)
 if event.phase == "release" then
 print("Button Released")
 end
end

local button = widget.newButton{id="b1",
 left=80,
 top=220,
 label="Tap",
 width=160,
 height=40,
 cornerRadius=12,
 onEvent=on_button
 }

For a full list of properties consult the Corona documentation here: http://developer.anscamobile.com/reference/index/widgetnewbutton

Corona – Audio

Corona makes it easier than anything to get sound into a project. The documentation says:

Sound Formats

  • All platforms support 16-bit uncompressed .wav files.
  • iOS and Mac Simulator support .mp3, .caf, and .aac.
  • Windows Simulator supports .mp3 along with .wav.
  • As of build 269, Android now supports .mp3 and .ogg formats.

So it looks like you can use wav, mp3, caf and aac on IOS. Since I’m focusing on the IOS platform I’ll stick with one of these formats. You can use garage band to generate AAC and MP3 files.

To get a sound to play you need to load the file creating a reference to the audio object in the process. Then tell that audio object to play.

Try it for yourself. Create a new Corona project, follow these steps:

  1. Create a folder to store your project.
  2. Create a new text file and save it into your folder with the name main.lua.
  3. Find a suitable sound file and copy it to the folder.

Add the following Lua code to your main.lua file. The file I for the example was named beep.mp3. Be sure to replace this name with the name of your sound file.

local mySound = audio.loadSound( "beep.mp3" )
audio.play( mySound )

Pretty simple huh? The first line loads your sound. The next line tells the sound to play.

Resources:

  1. cfxr – A sound tool for the Mac

Corona – Variables

A variable is a storage space for a value that your program will use.Imagine you are creating a game. You might want to keep track of the game score. You would use a variable to do this. Often your programs will have many variables that refer to lots of different things.To assign a variable a value use the equal sign. For example:

score = 0

You can think of variables in the same way that you used x and y in algebra. These letters were placeholders for many possible values. In Lua, like many other programming languages variables get a name. The name can be any combination of characters. You can use variables as placeholders for values that will change as your program runs. For example you might display your score by setting the text property of a Text Object. For example:

scoreText = display.newText(...)
score = 0
-- later in your program
scoreText.text = score

Variables are called variables because the stored values can change. As your program runs you can change the value assigned to a variables. You can assign a new value at anytime to a variable using the equal sign.

The example above declares two variables scoreText and score. The first holds a reference to a new Text Object. The second holds a number, 0 in this case.

score = 10000

Note: Lua doesn’t support composite assignment operators like += and -=. Instead you’ll need to use:

score = score + 100

In Lua variables can be Global or Local. All variables are Global unless specifically declared as Local. Global variables can be accessed anywhere in the program. Local variables can only be accessed in the code block where they were declared. Declare a Local variable with the key word “local” the first time it appears. For example:

core = 100
local color = "red"

Here “score” is a global variable and color is a local variable.

Scope

Scope is a term that refers to where a variable can be accessed. The scope Global variables is easy to determine. Since they are accessible everywhere.

Local variables on the other hand take a little more thought. Unlike global variables, local variables have their scope limited to the block where they are declared. A block is the body of a control structure, the body of a function, or a chunk (the file or string with the code where the variable is declared).

x = 10             -- global variable
local i = 1        -- local to the chunk

while i<=x do
   local x = i*2   -- local to the while body
   print(x)        --> 2, 4, 6, 8, ...
   i = i + 1
end

if i > 20 then
   local x         -- local to the "then" body
   x = 20
   print(x + 2)
else
   print(x)        --> 10  (the global one)
end

print(x)           --> 10  (the global one)

It is good programming style to use local variables whenever possible. Local variables help you avoid cluttering the global environment with unnecessary names. Moreover, the access to local variables is faster than to global ones.

 

 

 

 

 

Corona – Physics

Corona has a nifty physics engine built in. The physics engine is used to simulate the interactions of objects using real world effects like gravity and motion. Elements, called “bodies”, can properties like density, friction and bounciness, which make them behave like real objects in the real world. Imagine you threw a ball. It might fly through the air while gravity pulled it toward the earth. Then it might bounce when it hit the ground and bounce again when it a wall. If you wanted to create a similar effect in an app the physics engine would help you do this and make it look realistic.

Using physics in Corona

Using physics in Corona is surprisingly easy and straight forward. The first step is to import the physics class and turn the physics engine on.

local physics = require("physics")
physics.start()

The first line import the physics engine and the second turns it on. The first line stores a reference to the physics engine in a variable named “physics”, we’ll use this to talk to the physics engine. Notice the second line uses the “physics” variable to turn the engine on. As we go you’ll see we’ll use the name “physics” to create physics “bodies” and set other options having to do with the physics environment.

Create a body

Next create a display object of some kind. This can be an image or a shape, then create a physics “body” from that object. The body is controlled by the physics environment and essentially takes over the display object moving it as it might move with the effects of gravity and bumping into other “bodies”.

Here’s a simple example that creates an image turns it into a physics body.

local box = display.newImage("box.png")
physics.addBody( box, "dynamic", { density=1.0, friction=0.3, bounce=0.65 } )

Here we call physics.addBody() with three parameters. The first, a display object to create the body from, box in this example. The second sets the type of object this will, “dynamic” in this case. “Dynamic” objects can move around and bump into other object. Last is a table containing options for the object, density, friction and bounce in this example.

  • density – the weight or mass of an object
  • friction – how much energy the object loses over time
  • bounce – the amount of energy the object retains when bounces off another object

Try it for yourself

Try this out for yourself. Follow the instructions below.

  1. Create a folder to hold your project.
  2. Create a new text file and save it into your folder with the name main.lua.
  3. Next add the following to your main.lua file
local physics = require("physics")
physics.setDrawMode( "debug" )
physics.start()

Here I imported the physics library and set some options. I set the draw mode to debug. This will display simple shapes for your physics objects. Second I started the physics engine running.

Now add a shape. Add a small image to your folder to use a physics object. Make this a square or a circle about 20px in diameter.

local ball = display.newImage("ball.png")
ball.x = 160
ball.y = 30
physics.addBody( ball, "dynamic",{ density=1.0, friction=0, bounce=0.65, radius=10 } )

Here you imported your image and made a display object from it, with the name “ball”. Then positioned the ball at the top center of the screen. Then you created a physics “body” from your display object. This is a “dynamic” object so it will move around. I added the “radius” property and set the value to the radius of the ball image. Since my ball was 20px I used 10 as the radius. Adding radius makes the “body” circular.

Test your project. At this point the ball should fall down the screen as if it were pulled by the force of gravity. The same thing would happen if you dropped a real ball. Of course a real ball would not fall forever it would hit the ground at some point.

Make a static body

Next we’ll create a ground plane.

local floor = display.newRect(0, 0, 320, 10)
floor.x = 160
floor.y = 475
floor:setFillColor( 255, 0, 0 )
physics.addBody( floor, "static", {density=1.0, friction=0.3 } )

Rather than using an image this time I created a rectangle shape object, 320px wide and 10px tall. The new shape is named “floor”.  Next we positioned the floor at the bottom center of the screen. Then give it a fill color of red. Last we create a new “body” from the floor shape. Here the type is “static”. Static shapes don’t move.

Test your project again. This time the ball falls and bounces off the ground. Change the bounce value assigned to the ball body, notice the change.

Gravity

Change the gravity in your physics world with physics.setGravity(x,y). Gravity is a constant force that pulls object in one direction. Add the following to your main.lua.

physics.setGravity(0,0)

Test your project again, notice the ball goes nowhere. This time there is no gravity. We can use this setting to simulate a top down view. Try out a few different values for the x and y of gravity. Set this back to 0 and 0 when you’re satisfied you understand what is happening with gravity.

Add more walls

Add three more walls to create a box. Add the following to your project file.

local ceiling = display.newRect(0, 0, 320, 10)
ceiling.x = 160
ceiling.y = 5
ceiling:setFillColor( 255, 0, 0 )
physics.addBody( ceiling, "static", {density=1.0, friction=0.3 } )

local left = display.newRect(0, 0, 10, 480)
left.x = 5
left.y = 240
left:setFillColor( 255, 0, 0 )
physics.addBody( left, "static", {density=1.0, friction=0.3 } )

local right = display.newRect(0, 0, 10, 480)
right.x = 315
right.y = 240
right:setFillColor( 255, 0, 0 )
physics.addBody( right, "static", {density=1.0, friction=0.3 } )

Here I’ve added three more boxes like the floor. These make up the left and right walls and the ceiling.

Test your project again. You should see the new walls and there should be a wall on each edge of the screen.

 

Velocity

Next we’ll make the ball move by tapping the screen. With each tap we’ll give the ball some linear velocity. That’s velocity in a straight line.

local function onTouch(event)
 local x = ball.x - event.x
 local y = ball.y - event.y
 ball:setLinearVelocity( x, y )
end

Runtime:addEventListener("touch", onTouch)

Here I created a function, onTouch. This function is triggered when the screen is touched. The event object passed to the function contains an x and a y position of where the touch occurred. The first to lines in the function the difference between the touch x and y and the ball x and y. The last line calls the setLinearVelocity method of ball and uses the two values to push the ball away from were you touch the screen.

The line below the function adds an event listener to the screen. This is what will trigger the event when a touch occurs.

Test your project again. This time the ball should sit still until you touch the screen. When you touch the screen the ball should move way from the point where the touch occurred bouncing off the walls as it moves.

Here’s a few things to try for yourself.

  1. Try different values for gravity
  2. Try out different values for density, friction and bounce for the ball
  3. Try removing the line physics.setDrawMode( “debug” )
  4. Try changing changing from debug to hybrid physics.setDrawMode( “hybrid” )

 

Corona – Sprites

Sprites are similar to movieclips but more efficient. Where movieclips use a separate image for each frame of an animation. A sprite uses one single image that contains all of the frames. Mobile devices have limited memory and images take up most of the memory your projects might use. Using a single image where you once had several can dramatically cut down the amount of memory your app may be using.

Sprite Sheets

A sprite sheet is a single image that contains all of the individual images that make up an animated sequence of images. Here’s an example. This image contains three animated images of the saucer (the four spots in the center move). Each individual image is 48pixels wide by 21 pixels tall. I used a transparent png, where the red was transparent, in my original test. I had to fill in the transparent area or you would not be able to see the white image against the page here.

A sprite sheet can have more than one series of images. As a matter of fact you could have all of the images used in your project inside of a single sprite sheet. Note the iPhone has a maximum image size that is can work with. On earlier iPhones the max size is 1024 by 1024 while newer models support up to 2048 by 2048 pixels.

Try it for yourself

The artwork for this example is more difficult to create than the other examples you’ll need to pay close attention to how it is created and sized. You can use the example image above if you like.

  1. Create a new folder where you will store this project
  2. Create a new text file and save it to your folder with the name main.lua
  3. You’ll need an image containing each image of an animated sequence. That’s one image containing all frames of the animated sequence. See the example image above. Keep your images simple at first to avoid trouble.
  4. Note the height and width of each frame. Each frame should be exactly the same size. (this isn’t a requirement for using sprites in Corona, but it is required for the code sample below)

Add the following code to your main.lus file. You’ll need to change the file name of saucer_sprites.png to the name of your image file.

You’ll also need to change 48 to the width of your sprites and 21 to the height. These are the width and height of each individual frames.

 

-- Include the sprite
require "sprite"
-- name the image file containing your sprites, followed by the width and height of each sprite
local saucer_sheet = sprite.newSpriteSheet("saucer_sprites.png", 48, 21)
-- Create a set by naming the sheet and starting frame and number of frames
local saucer_sprite = sprite.newSpriteSet(saucer_sheet, 1, 3)

-- Now create new sprite, give it a name, set the starting frame, end frame,
-- and time between frames in ms, 0 means loop
sprite.add( saucer_sprite, "saucer1", 1, 3, 100, 0 )

-- Create a new Sprite in the display object so we can see it on the screen
local saucer = sprite.newSprite( saucer_sprite )
-- Position your sprite
saucer.x = display.contentWidth / 2
saucer.y = display.contentHeight / 2

-- Prep your sprite
saucer:prepare("saucer1")
-- Start the sprite playing
saucer:play()

Some resources:

Corona – Movie Clips

Often you will want to create a short animated clip. This is good for a lots of things especially games. A movieClip is an object that contains a series of images. Movieclips can play display their images in succession to create animated effect.

MovieClips are really a series of images loaded into to Corona and played in sequence. You could accomplish this with a Group containing all of the images and an array. Then writing an enterFrame function to cycle through the images in the array making each one visible in turn.

You could do all of that but, you don’t need to since someone over at Corona has all ready done it for you! This example uses the movieclip.lua file. You can find this in CoronaSDK/SampleCode/Graphics/MovieClip.

Create a new Corona project.

  1. Create a folder to work in
  2. Copy the movieclip.lua file from CoronaSDK/SampleCode/Graphics/MovieClip into the folder where you will be working
  3. Create a new text file and save it into the folder an name it main.lua
  4. Create a series of small images to use for the animated sequence. Imagine these images as frames in a movie. Save the images into the project folder

Add the following code to main.lua

-- Import an external library
local movieclip = require("movieclip")

-- Since we're importing a library we need to make a main function
-- to run after the library has loaded

-- Define the main function to initialize this program
function main()
 -- This line makes a new animated "movieClip" from the saucer images in the table
 saucer = movieclip.newAnim{"saucer_01.png", "saucer_02.png", "saucer_03.png"}

 saucer.x = display.contentWidth / 2
 saucer.y = display.contentHeight / 2

 -- Start the animation playing
 saucer:play()
end

-- Call main to start the program
main()

Corona – frame based animation

Transitions work well for situations when you want a motion to run from start to finish with a set length of time. For example you’d like to have en element move onto the page and stop in the center over 3 seconds. At other times you’ll want to create a motion that plays continuously. For example, you have object that moves back and forth across the screen for as long as it is on the screen. In these cases transition.to() doesn’t work so well. For these situations we can use the “enterFrame” event.

The enterFrame event

The enterFrame event is an event that us dispatched once every frame. Which of course brings up the idea of frames. Think of frames as the number of times Corona updates the screen. This is typically 30 times per second. So the enterFrame event is an event that is sent 30 times per second.

You can use the enterFrame event to do lots of things. A common purpose is animation. Imagine you had a object on the screen you added 12 degrees to it’s rotation 30 times each second. It would make a complete rotation every second.

Test the enterFrame event

Create a new Corona project

  1. Make a folder to work in
  2. Create a new text file and save into the folder with the name main.lua
  3. Copy a small image into your folder

In your main.lua file add the following code.

-- Make a new image
local invader = display.newImage("invader_04.png")

-- Position the image at a starting location off the left edge of the screen
invader.x = -80
invader.y = 160

-- Use this function move the image, this function will be run once each frame
-- each frame add 5 to the x. If x is greater than 400 move the image to the left
local function move(event)
 invader.x = invader.x + 5
 if invader.x > 400 then
 invader.x = -80
 end
end

-- Add an enterFrame event to the Runtime object
Runtime:addEventListener( "enterFrame", move )

Corona – Events

Think of notifications from the program about things that have happened in the program. Use events to determine when an object is tapped or when period of time has passed. Use events to animate things and react to user interaction.

Listeners and Handlers

Listeners are objects that have been assigned to respond to an event. Handlers are the functions that are run when an event occurs. Think of listeners as waiting for and notifying their handlers when the event occurs.

Most objects in Corona can be assigned a listener. Use the addEventListener() method to assign the listener. For example imagine you want a create an event is fired when you tap an image. You might write the following. Try it for yourself.

  1. Create a new folder to work in
  2. Open a new text file and save it to your folder with the name main.lua
  3. Copy an image to use in the example to your folder

Add the following code to main.lua:

-- Create an image and position it in the center of the screen
local invader = display.newImage("invader_04.png")

invader.x = display.contentWidth / 2
invader.y = display.contentHeight / 2

-- Define a handler
local function tapInvader( event )
 transition.to(invader, {time=1000, rotation=invader.rotation+360})
end

-- Add an event listener to the invader
invader:addEventListener("tap", tapInvader)

I added a few comments to the code to explain what is going on. Any line that begins with “–” is ignored and the rest of the line can be used to write a message or description of your code.

Test your project and tap the invader. With each tap it rotates 360!