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.
Related
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
I have two nodes one near another. And I want one node to be on top of another when I tap. I do so like this:
SKAction *moveUp= [SKAction moveByX:0 y:25 duration:0.1];
SKAction *moveDown= [SKAction moveByX:0 y:-25 duration:0.1];
SKAction *playerSequence = [SKAction sequence:#[moveUp,moveDown]];
[self.player runAction:[SKAction repeatAction:playerSequence count:1] withKey:#"attack"];
And instead I get that one node pushes the other (bots nodes created via editor and both body type is set to none).
I tried adding these to didMoveToView on both nodes:
node.physicsBody.dynamic = NO;
node.physicsBody.collisionBitMask = 0;
node.physicsBody.contactTestBitMask = 0;
node.physicsBody.affectedByGravity = NO;
I even tried setting velocity to 0 on Update. And still no effect.
Set your bit masks in
-(void)didBeginContact:(SKPhysicsContact *)contact
as shown in this post.
I think you have a timing issue if you set the bit masks in
didMoveToView
because only one of those will be run at a time and both physics bodies will need to mutually agree not contact each other.
You have to set the physics body to nil:
node.physicsBody = nil;
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.
Since JSTileMap extends SKNode, you can use the API to move and animate your tilemap like any other node. However, I keep getting this weird effect/glitch...
Code:
_tiledMap = [JSTileMap mapNamed:#"Cloud.tmx"];
if (_tiledMap) {
[self addChild:_tiledMap];
}
_tiledMap.position = CGPointMake(800, 0);
SKAction *scrollLeft = [SKAction moveTo:CGPointMake(600, 0) duration:4];
SKAction *scrollRight = [SKAction moveTo:CGPointMake(700, 0) duration:4];
SKAction *sequence = [SKAction sequence:#[scrollLeft, scrollRight]];
SKAction *repeat = [SKAction repeatActionForever:sequence];
[_tiledMap runAction:repeat];
Results:
As you can see, whenever the JSTileMap changes direction, depending if its left or right, the image gets cropped or something, I can't explain it. This doesn't happen if the node itself is a SKSpriteNode. I added numbers to the background image for visual reference.
EDIT
Further tests reveal that moving the JSTileMap's position manually (_tiledMap.position.x = x+1) in the update loop, has the same effect. It crops the image/tile when it animates left, and returns to normal when it animates to the right.
I found a work-around. Apparently the problem is that the first tileset column itself is being cropped for some reason (if anyone figures this out please let me know). So the solution is to create a tilemap that is 2 tile units wider than what your original tilemap dimension is. For example, if your tiles are set to 32x32 (tilemap of 1024x768), you should generate a tilemap of 1088x768 instead and start drawing after the first column.
See image below.
It seems I was using an old/unmaintained version of JSTileMap. Slycrel's version of JSTileMap addresses this issue.
https://github.com/slycrel/JSTileMap
I'm creating an ongoing learning project (basically I code while learning to use the framework in hope it will be useful for me and for someone else) for Sprite Kit (you can find it here if you are interested) but I'm facing some performance problems with my code.
The project puts cubes on the screen and make them falling. Here's the class that creates the piece
// The phisics for our falling piece:
// It will be a square, subject to gravity of 5: check common.h (9.8 is way too much for us)
self.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(self.size.width, self.size.height)];
self.physicsBody.dynamic = YES;
self.physicsBody.mass = 100;
self.physicsBody.collisionBitMask = piecesCollisionBitmask;
self.physicsBody.allowsRotation = NO;
and here is the scene file with the loop.
//schedule pieces
SKAction *wait = [SKAction waitForDuration:1];
SKAction *pieceIsFalling = [SKAction runBlock:^{
FLPPiece *piece = [[FLPPiece alloc] init];
[self addChild:piece];
}];
SKAction *fallingPieces = [SKAction sequence:#[wait,pieceIsFalling]];
[self runAction:[SKAction repeatActionForever:fallingPieces]];
I suspect that physics is behind my frame rate drop. I would like to stop physics execution on node while keeping it on the screen as soon as it collides with something else.
Is that possible? How can I do that?