Sprite Kit animateWithTextures lags - ios

I'm using texture atlases in my Sprite Kit game. I'm creating SKTextureAtlas object and store it's textures in array for each animation. So when I need some animation on my hero I call animateWithTextures sending it the corresponding array. There are some lags when I start animations. Is there some way to start animation smoothly?

I am sure there are few ways to get around this. What you need to do is to preload an atlases before your gameplay actually start. Just show a loading screen at the beginning of the game and preload your atlases.
You may try with + preloadTextureAtlases:withCompletionHandler:
[SKTextureAtlas preloadTextureAtlases:textureAtlasesArray withCompletionHandler:^{ /*Game Start*/}];
Another way to implement resource loading before everything else (and keep everything in memory) is described here in Adventure game example
For more details about loading assets asynchronously take a peek into code which can be downloaded from the link above.

had the same problem and I solved it in my game by not using atlases. So try this example:
-(void)makePlayerAnimation:(SKSpriteNode *)player
{
SKTexture *texture1 = [SKTexture textureWithImageNamed:#"texture1.png"];
SKTexture *texture2 = [SKTexture textureWithImageNamed:#"texture2.png"];
SKTexture *texture3 = [SKTexture textureWithImageNamed:#"texture3.png"];
SKAction *animationTextures = [SKAction animateWithTextures:#[texture1, texture2, texture3] timePerFrame:0.1];
[player runAction:animationTextures];
}
When you wish to activate animation do this:
[self makePlayerAnimation:myNode];
or
[self makePlayerAnimation:self.myNode];
Just depends how you declared it.
If you need to run animation forever, you can just add line at the end of previous method:
SKAction *repeat = [SKAction repeatActionForever: animationTextures];
Hope this helps.

Related

IOS SpriteKit Blurred Sprite with TexturePacker

I'm doing a project with IOS Sprite kit (Objective-C), I use TexturePacker to make my Sheet/Atlas ,In my scene view I only display a Character animation nothing more but I have an issue when I display my Sprite it is blurry.
The resolution of the image sprite are 512*512 (I think it's good), and the size of Sheets are 2048*2048.
I try many things on texturePacker to increase the quality but noting work, when I display my animation on TexturePacker directly the quality is good, but when I try on XCode, the result are blurry, I have try to play my character animation in a array animation and the result are not blurry (but this technique use to much memory) so I think the problem is TexturePacker
Has anyone had the same problem is would have a solution ?
Here is my code :
[self.scene setBackgroundColor:[UIColor clearColor]];
self.view.allowsTransparency = YES;
// load the atlas explicitly, to avoid frame rate drop when starting a new animation
self.atlas = [SKTextureAtlas atlasNamed:CHARACTER_ATLAS_NAME];
SKAction *walk = [SKAction animateWithTextures:CHARACTER_ANIM_IDLE timePerFrame:0.033];
self.sequence = [SKAction repeatActionForever:walk];
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithTexture:CHARACTER_TEX_HELLO_0];
sprite.size = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
sprite.position = CGPointMake(sprite.size.width/2, sprite.size.height/2);
[sprite runAction:sequence];
[self addChild:sprite];
Here is a comparison on the top sprite when I use the image array and that below with SpriteKit and Texturepacker ( you can see the difference especially at eye level )
Thanks for your help

SpriteKit Texture Atlas vs Image xcassets

I am making a game and I noticed that during some scenes, my FPS kept dropping around the 55-60FPS area (using texture atlas). This drove me nuts so I decided to put all my assets to the Images.xcassets folder and voila, steady 60FPS.
I thought this was a fluke or that I was doing something wrong, so I decided to start a new project and perform some benchmarks...
Apple's documentation says that using texture atlas's will improve app performance. Basically, allowing your app to take advantage of batch rendering. However...
The Test (https://github.com/JRam13/JSGlitch):
- (void)runTest
{
SKAction *spawn = [SKAction runBlock:^{
for (int i=0; i<10; i++) {
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:#"Spaceship"];
sprite.xScale = 0.5;
sprite.yScale = 0.5;
sprite.position = CGPointMake(0, [self randomNumberBetweenMin:0 andMax:768]);
SKAction *action = [SKAction rotateByAngle:M_PI duration:1];
[sprite runAction:[SKAction repeatActionForever:action]];
SKAction *move = [SKAction moveByX:1200 y:0 duration:2];
[sprite runAction:move];
//notice I don't remove from parent (see test2 below)
[self addChild:sprite];
}
}];
SKAction *wait = [SKAction waitForDuration:.1];
SKAction *sequence = [SKAction sequence:#[spawn,wait]];
SKAction *repeat = [SKAction repeatActionForever:sequence];
[self runAction:repeat];
}
Results:
Tests repeatedly show that using the xcassets performed way better than the atlas counterpart in FPS. The atlas does seem to manage memory marginally better than the xcassets though.
Anybody know why these results show that images.xcassets has better performance than the atlas?
Some hypotheses I've come up with:
xcassets is just better optimized than atlasas.
atlasas are good at drawing lots of images in one draw pass, but have bigger overhead with repeated sprites. If true, this means that if your sprite appears multiple times on screen (which was the case in my original game), it is better to remove it from the atlas.
atlas sheets must be filled in order to optimize performance
Update
For this next test I went ahead and removed the sprite from parent after it goes offscreen. I also used 7 different images. We should see a huge performance gain using atlas due to the draw count but...
First, revise your test to match this :
for (int i=0; i<10; i++) {
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:#"Spaceship"];
sprite.xScale = 0.5;
sprite.yScale = 0.5;
float spawnY = arc4random() % 768;
sprite.position = CGPointMake(0, spawnY);
SKAction *action = [SKAction rotateByAngle:M_PI duration:1];
[sprite runAction:[SKAction repeatActionForever:action]];
SKAction *move = [SKAction moveByX:1200 y:0 duration:2];
// next three lines replace the runAction line for move
SKAction *remove = [SKAction removeFromParent];
SKAction *sequence = [SKAction sequence:#[move, remove]];
[sprite runAction:sequence];
[self addChild:sprite];
}
Rerun your tests and you should notice that your framerate NEVER deteriorates as in your tests. Your tests were basically illustrating what happens when you never remove nodes, but keep creating new ones.
Next, add the following line to your ViewController when you set up your skview :
skView.showsDrawCount = YES;
This will allow you to see the draw count and properly understand where you are getting your performance boost with SKTextureAtlas.
Now, instead of having just one image , gather 3 images and modify your test by choosing a random one of those images each time it creates a node, you can do it something like this :
NSArray *imageNames = #[#"image-0", #"image-1", #"image-2"];
NSString *imageName = imageNames[arc4random() % imageNames.count];
In your code, create your sprite with that imageName each time through the loop. ie :
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:imageName];
In your SKTextureAtlas test, use that same imageName obviously to create each sprite.
Now... rerun your tests and take note of the draw count in each test.
This should give you a tangible example of what batch rendering is about with SKTextureAtlas.
It's no about rendering the same sprite image thousands of times.
It's about drawing many different sprites images in the same draw pass.
There is likely some overhead in getting this rendering optimization, but I think the draw count should be self explanatory as to why that overhead is moot when all things are considered.
Now, you can hypothesize some more :)
UPDATE
As mentioned in the comments, my post was to expose why your test was not a good test for the benefits of SKTextureAtlas and was flawed if looking to analyze it in a meaningful way. Your test was like testing for measles with a mumps test.
Below is a github project that I put together to pinpoint where an SKTextureAtlas is appropriate and indeed superior to xcassets.
atlas-comparison
Just run the project on your device and then tap to toggle between tests. You can tell when it's testing with SKTextureAtlas because the draw count will be 1 and the framerate will be 60fps.
I isolated what will be optimized with a SKTextureAtlas. It's a 60 frame animation and 1600 nodes playing that animation. I offset their start frames so that they all aren't on the same frame at the same time. I also kept everything uniform for both tests, so that it's a direct comparison.
It's not accurate for someone to think that using SKTextureAtlas will just optimize all rendering. It's optimization comes by reducing draw count via batch rendering. So, if your framerate slowdown is not something that can be improved via batch rendering, SKTexture atlas is the wrong tool for the job. right ?
Similar to pooling of objects, where you can gain optimization via not creating and killing your game objects constantly, but instead reusing them from a pool of objects. However if you are not constantly creating and killing objects in your game, pooling ain't gonna optimize your game.
Based on what I saw you describe as your game's issue in the discussion log , pooling is probably the right tool for the job in your case.

Batch render sprites with Spritekit

I'm learning ios game programming and I need to create my own tile background - we're migrating an infinite-map style game from java.
I have the following code rendering our background tile graphics inside a loop:
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:#"shallow_1.png"];
sprite.position = CGPointMake(x,y);
[self addChild:sprite];
However, I'm trying to find out how to properly batch render in spritekit. In java/opengl we'd apply the texture, add all the render positions, and then render everything at once - saving performance.
How can I properly batch render these tiles using spritekit? I can't find any information.
If you're planning to work with tilemaps, your best bet is KoboldKit.
It's a game engine for SpriteKit, and adds several features to the framework.
In includes support for time maps (Tiled Map Editor).
Load your texture once:
SKTexture *texture = [SKTexture textureWithImageNamed:#"shallow_1.png"];
Then, make all of your SKSpriteNode objects referencing that texture:
// inside loop
SKSpriteNode *node = [SKSpriteNode spriteNodeWithTexture:texture];

How to preload textures in Sprite Kit?

I have a few frames of animations on my node, and the first time I play the animation it lags, fps drops. Each next time is fine and dandy.
How do I preload the textures to make it work smooth?
I have this method to run when I load the game:
- (void)load
{
self.animationFrames = #[[SKTexture textureWithImageNamed:#"exp1"], [SKTexture textureWithImageNamed:#"exp2"],
[SKTexture textureWithImageNamed:#"exp3"], [SKTexture textureWithImageNamed:#"exp4"], [SKTexture textureWithImageNamed:#"exp5"], [SKTexture textureWithImageNamed:#"exp6"], [SKTexture textureWithImageNamed:#"exp7"], [SKTexture textureWithImageNamed:#"exp8"], [SKTexture textureWithImageNamed:#"exp9"]];
}
And this method to play animation:
-(void)playExplosionAnimation
{
self.size = CGSizeMake(250, 250);
SKAction *animation = [SKAction animateWithTextures:self.animationFrames timePerFrame:0.1];
[self runAction:animation completion:^{
self.hidden = YES;
}];
}
You should create a texture atlas and use SKTextureAtlas methods:
– preloadWithCompletionHandler:
+ preloadTextureAtlases:withCompletionHandler:
Here is what documentation says about this:
Sprite Kit creates a background task that loads the texture data from
the atlas. Then, Sprite Kit returns control to your game. After the
texture atlas is loaded, your completion handler is called.
If you need to preload multiple texture atlases at once, use the
preloadTextureAtlases:withCompletionHandler: method instead.

Changing SK Textures for "MouseOver" in Xcode 5.0

I have a sprite with a given texture using:
joyStickRight = [SKSpriteNode spriteNodeWithImageNamed:#"joyStick.png"];
And I'd like to change it when the user touches and holds the sprite. When I detect the touch, I try changing the sprite texture by calling the same function with a different image:
joyStickRight = [SKSpriteNode spriteNodeWithImageNamed:#"joyStick_rollOver.png"];
But this does not seem to work. Nothing changes.
This for an iPad application. I am creating the on screen elements with SKSpriteNodes.
This is likely to be related to variable scope. I'm guessing you are trying to modify another instance of 'joyStickRight' SKSPriteNode. This second instance would not have been added to the scene and therefore not taking any effect.
The only way i found out to change textures ist to swap them via action like this:
SKTexture *texture1 = [SKTexture textureWithImageNamed:#"texture1"];
SKTexture *texture2 = [SKTexture textureWithImageNamed:#"texture2"];
SKAction *swapTextures = [SKAction repeatAction:[SKAction animateWithTextures:#[texture1,texture2] timePerFrame:0.1] count:3];
[node (in your case joyStickRight) runAction:swapTextures];
I still hope this is not the only solution, and also wonder why it does not work when i run it once!!!

Resources