Corona – Sprites Simple Game

Here’s an example that builds off the last post about creating an explosion sprite. In this example we’ll create some alien sprites that move down the screen. When touched these aliens explode.

The explosion sprite sheet and code was taken from this post: Corona – Sprite Explosion.

For this example I used this sprite sheet for the alien: 

Continue reading Corona – Sprites Simple Game

Corona – Sprite Explosions

Sprites

Often you’ll want to create an animated object on the screen, have it play through an animated sequence then remove itself from the screen. In this example I’ll created an animated explosion. The explosion appears when you tap the screen, then removes itself once the sequence of frames is complete.

Sprite Sheet

Creating the sprite sheet. I used the explosion generator here: http://www.nuvorm.nl/?p=1. You’ll need to have the Flash player installed to use this. It generates a sequence of frames in a wide image. The iPhone 3 does not support images larger than 1024 and the 4 supports maximum dimensions of 2048. The explosion image generated from nuvorm.nl was 3999px wide. I had to take this into Photoshop and arrange the image into multiple rows.

I calculated the size of each frame by counting the frames and dividing by the width. Turns out I had 43 frames. This meant each frame 93 px wide. The original image was 100 pixels tall. I sized the image 400 px tall. Then I moved the rows of 10 frames to create a new image 10 frames wide by 4 frames tall. When I was done I had created the image below:

Note the last few frames didn’t have much in them so I dropped the last three frames and made the sequence 40 frames long.

Continue reading Corona – Sprite Explosions

Corona – Accelerometer

Accelerometer

The Accelerometer is built into all IOS and other handheld devices, it detects motion of the device, tilting or shaking. Corona handles this with the Accelerometer event.

Remote Test

The accelerometer is difficult to test with, since the Accelerometer events are not available in the simulator. This means that you need to build your project each time you want to test. Which tedious and slow. There’s a solution!

There are several apps that can be used to send accelerometer and other events from a real device to the simulator.

All of these apps are very similar. You install them on a device: iPhone, iPad, iPod Touch etc. Launch and Configure the app. Set up your Corona project to receive data from the device. This consists of adding a few lines of code to your main.lua file.

Continue reading Corona – Accelerometer

Corona – Physics

Corona Physics

Corona incorporates the Box2d physics engine. The physics engine allow you create objects that move and interact like real physical objects. The engine works in flat 2d space.

The Corona implementation of Box2d is simple and intuitive to use. making it incredibly easy to add physics based motion to any project.

Starting physics

To work with physics you’ll to load the physics library and start the physics engine.

Start the physics engine by loading it with:

local physics = require( "physics" )

From here you’ll create physics objects and control the general physics environment through the variable physics defined in the line of code above.

Then start physics with:

physics.start()

Note: You must call start physics, with the line above doing anything else with physics.

Continue reading Corona – Physics

Corona – Arranging Objects

Arrays and Objects

It’s very common to create a number of similar objects. An easy approach is to use a for loop to create the objects and an array to store references to the objects created.

Here’s a quick example with squares. The first few examples will create static object and arrange them a few patterns.

Random arrangement

The example will arrange the objects at random positions on the screen.

-- Define an Array to hold the objects

local square_array = {}

-- A loop to create a number of objects

for i = 1, 10, 1 do

-- Make a new shape object

local square = display.newRect( 0, 0, 30, 30 )

-- Position the object at a random x and y

square.x = math.random( 30, display.contentWidth - 30 )

square.y = math.random( 30, display.contentHeight - 30 )

-- Add the reference to the object in the Array

table.insert( square_array, square )

end

The example defines an array, then executes a loop creating 10 objects and adding them all to the array.

Continue reading Corona – Arranging Objects

Corona – Dragging Objects

Dragging Objects

Dragging objects on the screen is not difficult. There are a few steps that need to be followed.

Since a drag must begin on a touch down and end when you touch up. You’ll need to use a touch event, rather than a tap.

Focus describes which object is currently getting the computers attention. The dragging object needs to keep focus for the duration of the drag. If another object takes focus in the middle of the drag our object may stop moving in the middle of a dragging unintentionally.

To make the drag look best we will want the dragged object to move a distance relative to it’s center and the location of the initial touch. Without this offset the object will shift to align it’s center with your finger when the touch begins.

When the drag is finished we need to return focus to the stage. This will allow other objects to take focus.

-- make an object to drag

local box = display.newRect( 0, 0, 100, 100 )

box.x = display.contentCenterX -- Move the object to the

box.y = display.contentCenterY  -- center of the screen

-- This function handles touch events on the object

local function on_touch( event )

-- Get the target object

local target = event.target

-- Check the phase of the event. Here the drag begins

if event.phase == "began" then -- When the event begins

local parent = target.parent -- get the parent object

parent:insert( target ) -- move the drag object to the top

-- The dragging object needs to keep focus

display.getCurrentStage():setFocus( target )

target.isFocus = true -- Mark this object as having focus

-- Get the offset from center of the object to the location

-- of the event

target.offsetX = event.x - target.x

target.offsetY = event.y - target.y

-- This phase handles moving the object

elseif target.isFocus and event.phase == "moved" then

target.x = event.x - target.offsetX -- Position the object

target.y = event.y - target.offsetY -- using the offsets

-- This phase ends the drag

elseif event.phase == "ended" or event.phase == "cancelled" then

display.getCurrentStage():setFocus( nil ) -- reset focus

target.isFocus = false -- mark this object as no longer having focus

end

end

-- Add this event listener for touch events to the dragging object

box:addEventListener( "touch", on_touch )

This example was taken from: http://developer.anscamobile.com/content/drag-me. This simplifies the Drag Me example to it’s essential code.

Corona – More Easing types

More easing types

The easing types provided out of the box with Corona are limited. Some of the classic easing types that people have long considered standard, like elastic, just aren’t there.

Fear not, these can be added through an external library. I found some code on the Corona site here: https://developer.anscamobile.com/code/more-easing.

Note: The discussion talks about changes and modifications to the first code block presented. The code I’m using here comes from further down the page at post #7.

This library expands the easing types to include the following new types:

  • easeIn
  • easOut
  • easInOut
  • easeOutIn
  • easeInBack
  • easeOutBack
  • easeInOutBack
  • easeOutInBack
  • easeInBounce
  • easeOutBounce
  • easeInOutBounce
  • easeOutInBounce
  • easeInElastic
  • easeOutElastic
  • easeInOutElastic
  • easeOutInElastic

These add a lot more possibilities to motion created with transition.to()

Here’s some sample code. The example below imports the new easing library and then applies an elastic ease to an object.

To make this example work you’ll need to get the code from the link above and save into a file named easingX.lua. This new file will need to be in the same folder as main.lua.

-- The easing methods included here expand on the default easing
-- included with Corona. The extra library of easing formulas is
-- imported through the easing.lua. The code for this was obtained
-- at: https://developer.anscamobile.com/code/more-easing
-- Note: The discussion talks about changes and modifications to
-- the first code block presented. The code I'm using here comes
-- from further down the page at post #7.
-- require the easingX library
easingX = require "easingX"

local box = display.newRect( 0, 0, 50, 50 )

box.x = display.contentCenterX

-- Note the use transition in the parameters.
-- get the newer easing ypes from easingX which was required above.
transition.to( box, {time=3000, y=display.contentCenterY, transition=easingX.easeOutElastic} )

Here you can see the box moves with an elastic quality swinging back and forth past the  target value before settling into stop.

Corona – Animation

Corona Animation Overview

Animation can be looked at in two different categories: Object animation and Frame animation.

Object animation would be defined as moving objects on the screen by setting the x, y or other properties. Frame based animation would be animation created by cycling through a series of images.

These two types of animation can be used together. For the first part of this discussion we will look at each separately.

Continue reading Corona – Animation

Corona – Display Objects

Display Objects

Anything you can see on the screen is considered a display objects. Display objects can be images, text, shapes or almost anything you can think of.

Corona provides a few display object types. You can divide these into three broad categories:

  • shapes
  • text
  • images

An object in programming terms is defined as a collection of properties and methods. properties are variables that belong to the object and methods are functions that belong to the object.

For example a shape object might have properties of x and y. The x and y properties might set the location of the object on the x and y axis.

Many of the properties and methods of display objects are common to all display objects. While other properties and methods are specific to certain display objects. For example the x and y property exists for all display objects. The text property only applies to text objects.

The best way to get an idea of how to work with display objects is make a few.

Create a new Corona project and add the following code the main.lua file.

local box = display.newRect( 0, 0, 50, 100 )

This creates a new rectangle with it’s left edge at 0, top edge 0 and a width of 50 and height 100 pixels.

display.newRect( left, top, width, height )

This method creates a new rectangular shape. The shape has a solid color fill.

I have declared a new local variable box to hold a reference to the new box that was created. Through this variable you can access all of the properties and method of new object. Here are a few examples:

local box = display.newRect( 0, 0, 50, 100 )

-- Set the x and y to position the
-- box in the center of the screen
box.x = display.contentCenterX
box.y = display.contentCenterY

-- Set the fill color of the box
box:setFillColor( 33, 111, 255 )

-- Add a stroke
box.strokeWidth = 3

-- Set the stroke color
box:setStrokeColor(255, 222, 123 )

In general all display objects act the same way. Different types of display objects will have properties or methods that specific to them. For example the setTextColor() method only applies to text objects.

Corona – for loop

The for loop

Often when writing a program you will want to repeat the same process. Luckily there is a construct designed especially for this.

Meet the for loop

The for loop is a construct that repeats a block of code a set number of times. Here’s an example that counts from 1 to 10:

for count = 1, 10, 1 do
    print( “count:”, count )
end

Here count is a variable assigned a starting value of 1. 10 is defined as the ending value for count. And, 1 is the value that will increment count with each repeat. That is 1 will be added to count with each repeat.

The code between do and end is repeated with each count.

The variable used to keep track of the loop can use any name you like. For example you’ll often see i used here.

for i = 1, 12, 1 do
    print( “Count:”, i )
end

Essentially the loop counts from the first number to the second number, adding or stepping with the third number.

Count backwards

For loops can count forward or backward. Try this example:

for count = 10, 1, -1 do
    print( “Count:”, count )
end

This time the loop starts at 10 and counts by subtracting 1 each time until count reaches a value of 1.

Stepping by values other than 1

The step can also be any value you like. For example:

for count = 2, 10, 2 do
    print( “Count:”, count )
end

This time the loop begins the count on 2, and steps 2 with each repeat, counting the event numbers from 2 to 10.

A few notes on loops

When a loop is run the computer does not up the screen. Therefore you can not use a loop to animate objects! All other processes are suspended until the loop completes.

That said you can use a for loop inside of an enterFrame handler to animate a list of objects.

Why use a loop?

Many times you will have lists of things to work with. Imagine a game like Tetris. A for loop makes a good choice for updating all of the tiles on the board when the game updates.

Space Invaders type games might use a for loop to loop through all of the invaders to move and check for collisions.

Any program might us a for loop to loop through a list of display objects to position and initialize them when the program begins.