Small example for CoronaSDK using PhysicsEditor to create the shapes and TexturePacker for the sprite sheets.
Full source code to this example project is available on GitHub.
As requested on the Corona forum I created a small example using PhysicsEditor to create the shapes and TexturePacker for the sprite sheets.
I use the excellent SpriteGrabber
class from the corona forum to split the sheet.
local physics = require("physics")
physics.start()
This code loads SpriteGrabber
and then loads our sprite sheet.
local grabber = require("SpriteGrabber")
spriteSheet = grabber.grabSheet("spritesheet")
To add a sprite you need to extract it from the sprite sheet, creating a sprite. Sprites can be addressed by their name:
local bkg = spriteSheet:grabSprite( "bkg_cor.png", true)
With this code block you initialize a floor sprite, setting it's position. The bar is taking a rectangulars standard shape.
The second block initializes a second bar shape which sits above the other. With this the impression can be created that the sprite sinks in the floor a bit.
local bar = spriteSheet:grabSprite("bar.png", true)
bar.x = 160; bar.y = 430
physics.addBody( bar, "static", { friction=0.5, bounce=0.3 } )
-- create floor shape only for the looks
local bar2 = spriteSheet:grabSprite("bar2.png", true)
bar2.x = 160; bar2.y = 440
To load the physics data created with PhysicsEditor simply require the file and
call the function physicsData
:
-- load the physics data, scale factor is set to 1.0
local physicsData = (require "shapedefs").physicsData(1.0)
This code enables hybrid drawing mode - it shows the shape itself but also overlays the shape's collition shapes.
physics.setDrawMode( "hybrid" )
This function chooses a random object by it's name, creates a sprite using spriteSheet:grabSprite
and then
attaches a physics body which is retrieved from physicsData
by calling addBody
.
Finally the object is set to a random position allowing it to drop onto the scene:
function newItem()
names = {"orange", "drink", "hamburger", "hotdog", "icecream", "icecream2", "icecream3"};
name = names[math.random(6)];
-- set the graphics
obj = spriteSheet:grabSprite(name..".png", true);
-- set the shape
physics.addBody( obj, physicsData:get(name))
-- random start location
obj.x = 60 + math.random( 160 )
obj.y = -100
end
Finally this function is called from a timer, spawning more and more items over time:
local dropCrates = timer.performWithDelay( 500, newItem, 100 )