Problem: I have a long duration frame-based animation for which i have created many spritesheets (e.g. 50 spritesheets with 10 images in each - 2 MB per spritesheet). It takes noticeable time (and memory) to pre-load all 50 spritesheets before the animation can be played using code based on the example code snippet below (this is suggested in the corona docs):
local function spriteListener( event )
thisSprite = event.target -- "event.target" references the sprite
if ( event.phase == "ended" ) then
sequenceNumer = sequenceNumer + 1;
if (sequenceNumer <=10) then
thisSprite:setSequence(filenameArray[sequenceNumer])
thisSprite:play()
end
end
end
local spriteWidth = 551
local spriteHeight = 401
local numFrames1 = 15
local startFrame = 1
frameInfoSet1 = {width = spriteWidth , height = spriteHeight, numFrames = numFrames1}
filenameArray = {"001-015","016-030","031-045","046-060","061-075","076-090","091-105","106-120","121-135","136-150"}
fullSequence =
{
{name=filenameArray[1], sheet=graphics.newImageSheet("spritesheets/" .. filenameArray[1] .. ".png", frameInfoSet1), start = startFrame, count=numFrames1, time=2250, loopCount=1},
{name=filenameArray[2], sheet=graphics.newImageSheet("spritesheets/" .. filenameArray[2] .. ".png", frameInfoSet1), start = startFrame, count=numFrames1, time=2250, loopCount=1},
{name=filenameArray[3], sheet=graphics.newImageSheet("spritesheets/" .. filenameArray[3] .. ".png", frameInfoSet1), start = startFrame, count=numFrames1, time=2250, loopCount=1},
-- more such spritesheets are loaded further...
}
firstSpriteSheet = fullSequence[1]["sheet"]
sequenceNumer = 1
tt = display.newSprite (firstSpriteSheet, fullSequence)
tt.x = display.contentWidth/2 ; tt.y = display.contentHeight/2
tt:addEventListener( "sprite", spriteListener )
tt:play()
However, what i would like to achieve is a "streaming" version of this technique. i.e. I will load only 3 spritesheets out of the total of 50, therefore requiring say 6 MB to start playing the animation and keep loading additional spritesheets as the already loaded ones keep playing. So, to illustrate further, i load sheets 1,2,3 and start playing the animation and load sheet 4 by the time sheet 1 is finished, load sheet 5 by the time sheet 2 is finished and so on.
Any advice is appreciated ! Thanks in advance.
I see this is old question, but I will add thoughts from my expirience:
This is not an easy task, but it's possible
Preload sheets before you go
I suggest to add simple loading scene, where you will show progress bar while loading.
local filenameArray = ... -- this is from your code
local preloadedSheets = {}
local function enterFrameLoading()
local nextSheetToLoad = #preloadedSheets + 1
if (nextSheetToLoad > #filenameArray) then
Runtime:removeEventListener("enterFrame", enterFrameLoading)
-- go to game scene if you are using scenes
return
end
preloadedSheets[nextSheetToLoad] =
graphics.newImageSheet("spritesheets/" .. filenameArray[nextSheetToLoad] .. ".png", ??)
updateProgress(nextSheetToLoad) -- this function will update UI, i.e. progress bar, text, etc
end
Runtime:addEventListener("enterFrame", enterFrameLoading)
After preloading all sheets will be in memory, so you shouldn't have performance issues
Use multiple sprite objects, created on demand
You can create new objects inside spriteListener - again, store all sprites inside a table and use .isVisible = false to hide old sprites
Combine solutions 1 and 2
You can create sprite objects with just 3 sequences. Then preload other sheets in enterFrame listener like I showed above.
When preloading is finished you want to destroy old sprite and create new with the same sequence and frame
Let me know if you need more information on this
Related
I'm getting a (a nil value) error when i try to do this :
player = display.newSprite( imageSheet, "sequenceDataPlayer"..math.random(1, 7) )
Looking at a test print :
print ("sequenceDataPlayer"..math.random(1, 7) )
It prints the data oky 'sequenceDataPlayer1'
What Im i doing wrong here ?
Your print statement is just printing the string "sequenceDataPlayer" concatenated with a random number between 1 and 7.
It took me a little while to figure out how to use sprites in Corona, but here's how I do it. I'll use Player for the variables since that's what you're using.
First I create an options variable to get the frames from my Player.lua file:
optionsPlayer =
{
frames = require("player").frames,
}
Then I create a variable for the image sheet:
playerSheet = graphics.newImageSheet( "player.png", optionsPlayer )
After that, I create a variable to set up the name, the sequence of frames, the time it takes to play, and set how many times it will loop:
spriteOptionsPlayer = { name="Player", start=1, count=10, time=500, loopCount = 1}
Finally, I create the new sprite:
spriteInstancePlayer = display.newSprite( playerSheet, spriteOptionsPlayer )
Once I've done all this, I usually set up the x and y positions, xScale and yScale, and other properties along with adding it to a display group.
Last of all, then I play the sprite somewhere:
spriteInstancePlayer:play()
From what it looks like, you want to have 7 different sprites to choose from. Personally, I would just create seven different sprites using all of the steps above and then put them in a table.
sprites = { spriteInstancePlayer, spriteInstancePlayer2, spriteInstancePlayer3, etc.. }
Then when I wanted to play them, I would set the position and visibility and just do:
r = math,random(1, 7)
sprites[r].x = x position
sprites[r].y = y position
sprites[r].isVisible = true
sprites[r]:play()
Of course, then I would want to set listeners to either completely remove the sprite or set the visibility to false when it's done playing, there's a collision(you'd have to add a physics body and set that all up), or whatever else might happen...
There are probably simpler ways to do it, but that's what I do.
Hope this helps.
Hi I've been wondering this for a while and it's causing me lots of problems not knowing more about how to reference / specify all indexes of a spawned enemy on the screen at one time.
Say when my character dies I want all the enemies on the screen at that time to move away from my dead character as the screen fades out. Simply calling 'enemy1' only makes one (the last spawned I think) do as it's told.
Here is my enemy spawn script:
local spawnTable2 = {}
local function spawnEnemy()
enemy1 = display.newSprite( group, sheetE, sequenceData2 )
enemy1.x=math.random(100,1300)
enemy1.y=math.random(360,760)
enemy1.gravityScale = 0
enemy1:play()
enemy1.type="coin"
enemy1.objTable = spawnTable2
enemy1.index = #enemy1.objTable + 1
enemy1.myName = "enemy" .. enemy1.index
physics.addBody( enemy1, "kinematic",{ density = 0, friction = 0, bounce = 1 })
enemy1.isFixedRotation = true
enemy1.type = "enemy1"
enemy1.timer = nil
enemy1.enterFrame = moveEnemy
Runtime:addEventListener("enterFrame",enemy1)
enemy1.objTable[enemy1.index] = enemy1
hudGroup:toFront()
return enemy1
end
To reference all objects, you would need to have two things.
A Counter
Loop
First make a counter:
counter = 0
Every time the funciton is called have a counter:
counter = counter + 1
For tables, you would do something like this:
spawnTable2[counter].x=math.random(100,1300)
Then when you want to remove the object, you would just do this:
display.remove(spawnTable2[counter])
Just keep in mind, everything you do to manipulate that object will have to be inside that function. Good luck and hope this helps.
I am attempting to add/remove objects from the physics engine (addBody() and removeBody()) in an app I am working on. The app I am working on is modular so the issue is in one of two files.
The objects file (TransmitterObject) or the main file (main):
This is the relevant code for both:
main.lua
local physics = require("physics")
physics.start()
physics.setGravity(0,0)
physics.setDrawMode( "debug" )
local TransmitterObject = require("TransmitterObject")
function updateGame(event)
if(ITERATIONS % 100 == 0) then
tran1:activate() --create new physics object here
end
ITERATIONS = ITERATIONS + 1
--print(ITERATIONS)
end
Runtime:addEventListener("enterFrame", updateGame)
TransmitterObject.lua
function transmitter.new(props) --constructor
Transmitter =
{
x = props.x,
y = props.y,
receivers = props.receivers
}
return setmetatable( Transmitter, transmitter_mt )
end
function transmitter:activate()
local group = math.random(1, #self.receivers)
local receiver = math.random(1,#self.receivers[group])
local x , y = self.receivers[group][receiver][1], self.receivers[group][receiver][2]
local d = math.sqrt(math.pow((self.x-x),2) + math.pow((self.y-y),2))
local dx = math.abs(self.x - x)
local angle = math.deg(math.acos(dx/d))
local beam = display.newRect(self.x,self.y, d, 10)
beam:setReferencePoint(display.TopLeftReferencePoint)
beam.rotation = 180 + angle
beam:setFillColor(0,255,0)
beam.alpha = 0
local function add(event)
physics.addBody(beam, "static")
end
local function delete(event)
physics.removeBody(beam)
end
transition.to( beam, { time=1000, alpha=1.0, onComplete=add } )
transition.to( beam, { time=1000, delay=2500, alpha=0, onComplete=delete})
end
Now let me try to describe the issue a little better. basically every 100th time that 'enterFrame' fires I tell the transmitter object (tran1) to call its function 'activate'
which then preforms some basic math to get coordinates. Then it creates a rectangle (beam) using the calculated information and sets some properties. That is all basic stuff. Next I tell it to transition from not visible (alpha = 0) to visible over the span of 1 second. When does it is to call the function 'add' which adds the object to the physics engine. Likewise with the next line where it removes the objects.
That being said, when i set physics.setDrawMode( "debug" ) the beam object appears as a static body, but does not accept collisions. Does anyone know why the above code would not accept collisions for the beam object?
Keep in mind I have other objects that do work properly within the physics engine.
Wow, I'm answering super late!
On collisions, modifying bodies aren't supported.
What I propose you is to create a new function,
local function addBody ( event )
physics.addBody(ball, "static")
end
and in your collision event you have to add this,
timer.performWithDelay(500, addBody)
The only thing that may cause some problems it's the delay, but as the collision doesn't take too much time it should be ok.
Sorry for this necroposting,
It's just to help other people that may have that problem,
Fannick
Apologies for the incredibly noob question, but I'm new to Lua, very very rusty at any code, stuck and can't find the solution!
I'm creating a series of random images on screen using:
for count = 1, 6 do
r = math.random ( 1, 5 )
mpart[count] = display.newImage ("mpart" .. r .. ".png")
mpart[count].y = 680
mpart[count].x = x
mpart[count].spawnednew = false
x = x + 170
mpart[count]:addEventListener ("touch", onTouch)
end
How do I know which object is being touched/moved in the function "onTouch", and how do I add a property to it, e.g.
mpart[1].spawnednew == true
Your onTouch function should have an event parameter passed in. The touched image can then be found by in event.target.
Well first off, lins is spot on about how to reference the touched object: the 'event' parameter of the listener function includes the value 'event.target'
As for adding new data to the touched object, that's as simple as 'event.target.moved = true' and now the object has data at object.moved
I have created a sprite sheet which plays continuously,
local sheet3 = sprite.newSpriteSheet( "sample.png",400,317)
local spriteSet3 = sprite.newSpriteSet(sheet3, 1, 8)
sprite.add( spriteSet3, "puma", 1, 8, 1000, 0 ) -- play 8 frames every 1000 ms
local instance3 = sprite.newSprite( spriteSet3 )
instance3.x = 2* display.contentWidth / 4 + 30
instance3.y = baseline - 5
instance3.xScale = .5
instance3.yScale = .5
instance3:prepare("puma")
instance3:play()
As we know spritesheet shows image sequence in loop. I want to stop play of image sequence after it completes one loop.
Anybody know how can i do this? or at least provide me any link to help me out to solve this problem?
When you define the animation in the first place you set whether or not to loop:
http://developer.anscamobile.com/reference/index/spriteadd
Alternatively if you need to adjust the animation programmatically (ie. loop until the player does something) then you can set an event listener and call pause() when the loop event happens:
http://developer.anscamobile.com/reference/index/spriteinstanceaddeventlistener