create a CCSprite from part of a CCSprite/CCSpriteFrame/CCSpriteBatchNode - objective-c

can you create a new CCSprite from a part of a CCSprite within a CCSpriteBatchNode?
For a long time, I've used SpriteFrameCache and BatchNode without a 100% understanding of the two, in particular how they relate to the textureCache. I could use some clear advice to accomplish the following:
Currently, I load a texture atlas into CCSpriteBatchNode and the frame list into the CCSpriteFrameCache and generate a sprite in what I think is basic standard fasion
CCSpriteBatchNode *batchNode = [CCSpriteBatchNode batchNodeWithFile:#"textureAtlasImage.png"];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"textureAtlasFrames.plist"];
CCSprite * gameObject = [CCSprite spriteWithSpriteFrameName:#"gameObject.png"];
[self addChild:batchNode];
[batchNodeaddChild:gameObject];
For the sake of simplicity with the question, What I'd like to do is divide gameObject into 4 pieces programatically (rather than divide the original image into four pieces and adding each into the textureAtlasImage.png individually).
From reading, I'm thinking something like:
CCSpriteFrame * gameObjectFrame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:#"textureAtlasFrames.plist"];
CCTexture2D * gameObjectIndividualTexture = [[gameObjectFrame] texture];
CCSpriteFrame * gameObjectPartFrame = [CCSpriteFrame frameWithTexture:gameObjectIndividualTexture offset: rectInPixels: ] ;
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFrame:gameObjectPartFrame name:#"gameObjectPart1"];
But my questions then are:
Is this already in the batchNode? If not, how do I actually create the sprite out of the gameObjectPart1 using batchNodes?
Is it wasteful to add another spriteframe to the cache that duplicates data elsewhere?

You should be able to adjust the texture rect after creating the sprite. Create four sprites using the same sprite frame, then set each sprite's texture rect to one of the 4 smaller regions you want them to use.
Use the sprite.textureRect property to get the CGRect with the original size and change the size respectively origin. For example the lower left rectangle can be created by setting textureRect to the same rect but with size.width and size.height halved.

Related

SpriteKit: moving sprite infinitely cause the frame sometimes incontinuous

all.
I am now developing an ios game using sprite kit.The game mechanics include: infinitely scroll sprites from top to bottom.
My game scene holds just 3 sprites,top,middle,bottom.
I have dozens of sprite images,so my solution is dynamic create 3 sprites ( so the sprites can fill the whole screen),when the bottom sprite is off screen,then destroy it;when the top sprite
goes down the top frame,create a new sprite node,then exchange the bottom,middle,top sprite.
The pseudo code:
in the interface file:
- GameScene:SKScene
{
...
SKSpriteNode *_topSprite;
SKSpriteNode *_middleSprite;
SKSpriteNode *_bottomSprite;
...
}
in the implementation file:
- (void)update:(CFTimeInterval)currentTime
{
// 1 compute time interval
// 2 update sprite node
_topSprite.position move down 100*timeInterval
_middleSprite.position move down 100*timeInterval
_bottomSprite.position move down 100*timeInterval
// 3 crop the off-screen bottom sprite node
if (_bottomSprite is offScreen)
{
[_bottomSprite removeFromParent]
}
// 4 check the highest sprite position visible
// if the highest position is below the frame top,then create new sprite
_bottomSprite = _middleSprite;
_middleSprite = _topSprite;
_topSprite = [self createNewNode]; // random a sprite image
}
the game fps is 60,and the nodes counts is not increasing.
All seems good,but i found sometimes the game just suddenly has a very shot choke causing the moving frame not continuous.
In my instinct,I thought the main reason is caused by step 4.
But I don't have any idea to solve it.
Any suggestions will be appreciated.
Here is the createNewNode method:
- (SKSpriteNode *)createNewNode {
NSString *blockName = [self randomImageName];
SKSpriteNode *sprite = [[SKSpriteNode alloc] initWithImageNamed:blockName];
sprite.position = _highestPosition;
sprite.anchorPoint = CGPointMake(0.5, 0);
NSLog(#"putAnotherNodeOnTop %#", blockName);
[self addChild:sprite];
return sprite;
}
A couple of suggestions.
Since you are using the same three images, you don't need to re-create the sprites each time. It should be less expensive to set the hidden value to YES, move the sprite somewhere, set the texture and then show it again with hidden to NO. SpriteKit doesn't draw hidden nodes, or ones off screen.
Your code basically asks for a PNG on disk every frame in update when createNewNode: is called. It should be more performant to load the textures in memory and assign them to sprites as needed. If you have just a few, making them SKTexture instance variables would be an easy way to do it.
Use spritesheets (texture atlases), it is much faster to draw an image from memory at mapped coordinates than to load it from disk each time. For example with three images in a spritesheet this can be a single draw call. From disk this is three separate draw calls.
You are returning a sprite and adding it to the scene in the createNewNode: method. Maybe that is what you want for some reason. It stood out as possible duplicate effort.

Draw waveform in NSView

I need to draw a waveform in an NSView. (I have all the samples in an array). The drawing must be efficient and really fast without clipping, flickering, etc, it must be smooth. The waveform will be "moving" according to the song position and some changes to the samples (DSP processing) will be shown as visual representation onto NSView in realtime.
I'm familiar drawing lines, arcs, etc onto canvas objects and I have developed apps doing such things but not on Mac OS X ...
I want to ask if anyone can guide me where to start drawing! Core Animation, OpenGL, simple override drawing methods, ??, etc. Which would be the best practice - API to use?
I would keep it simple and create an NSView subclass with an audioData property that uses Cocoa drawing. You could call [view setAudioData:waveArray] which would in turn call [self setNeedsDisplay:YES].
In your drawRect: method you could then iterate through the samples and use NSRectFill() accordingly. Here sample's value is between 0 and 1.
- (void)drawRect:(NSRect)dirtyRect {
[[NSColor blueColor]set];
for (id sample in self.waveArray) {
NSRect drawingRect = NSZeroRect;
drawingRect.origin.x = [self bounds].origin.x;
drawingRect.origin.y = [self bounds].origin.y + ([self.waveArray indexOfObject:sample]/([self.waveArray count] - 1.0));
drawingRect.size.width = [self bounds].size.width/[self.waveArray count];
drawingRect.size.height = [self bounds].size.height * [sample value];
NSRectFill(drawingRect);
}
}
This code isn't exact, and you should be sure to make it more efficent by only drawing samples inside dirtyRect.
I would start with a really long and thin image to represent a single bar/column for the waveform.
My plan would be to have a NSTimer that moves all bars of the wave one to the left every 0.01 seconds.
So something like this in the loop.
for (int x; x < [WaveArray count] ; x++)
{
UIImageView * Bar = [WaveArray ObjectAtIndex: x];
[Bar setCenter:CGPointMake(Bar.center.x-1,Bar.center.y)];
}
Now all you have to do is create the objects at the correct hight and add them to the WaveArray and they all will be moved to the left.

Using setTexture for animating in Cocos2d?

Let's say that I got 120 image files in my project. And I want to animate a sprite with all of them.
I was thinking about this method:
CCSprite *temp = [CCSprite spriteWithFile:#"TheNextSprite.png"];
[sprite setTexture:[temp texture]];
The above code will run like once every 0.03 seconds.
sprite is my animated CCSprite.
temp is simply a temporary CCSprite initialized with the image file for the next animation frame, so I can take its texture later.
Is that way efficient? I heard that I could use CCAnimate with a CCSpriteBatchNode, but this is only for one single sprite. Plus I got 120 (big) frames - they won't fit in a 2048x2048 texture canvas.
Have a look at the CCAnimation, CCAnimate and CCSpriteFrame classes.
Sprite frames are what you are trying to mimic, a 'piece' of a texture to which a sprite is mapped. They are best used when combined with spritesheets, not all of the sprites in the animation need to be in the same sprite sheet.
CCAnimation allows you to create an animation out of a sequence of such frames.
And CCAnimate allows you to run that animation as an action:
[node runAction:[CCAnimate actionWithAnimation:animationInstance restoreOriginal:NO]];

Changing sprite texture from a CCSpriteBatchNode

I am trying to change the texture of a sprite that I create from a SpriteBatchNode.
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA4444];
spritesBgNode = [CCSpriteBatchNode batchNodeWithFile:#"playingCards.pvr.ccz"];
[self addChild:spritesBgNode];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"playingCards.plist"];
I searched and found examples that use
Texture2D *texture = [[Texture2D alloc] initWithImage:myUIImage]
[sprite setTexture: texture];
So my questions is: how do I get the image from my batchNode file? Or do I use another method to get a reference to the image in my playingCards.pvr.ccz file.
UPDATE
First off thanks for the response. So I have mySprite with the image of a King using the code snippet you provided. But I want to change the sprite's texture to display the back of the card (so it can be played face up or down) I have both images inside CCSpriteBatchNode.
But as you point out "You can't get the image from a batchNode", so I can't use [[Texture2D alloc] initWithImage:myUIImage]
So do I go about changing the sprite's image from face up to face down.
Thanks
If you want to display the images in your .pvr.ccz file to the screen then add the following code:
CCSprite * mySprite = [CCSprite spriteWithSpriteFrameName: #"name of sprite frame"];
[spritesBgNode addChild: mySprite];
Basically, to display parts of your batchNode, you need to add a sprite to it. The name of the sprite frame is in the .plist file you added to the FrameCache.
You can't get the image from a batchNode. UIImage is the iPhone API type of image, not cocos2d. In cocos2d, initWithImage:(UIImage*)image is provided for convenience.
If you use [[Texture2D alloc] initWithImage:myUIImage], the UIImage is used to create an NSData object, and [texture initWithData: data] is called internally. The image isn't stored for later use.
Update
The sprite works as a 'view to a batchNode' in this case. To view a different part of the batch node, change the frame of your sprite.
[mySprite setDisplayFrame:
[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName: #"back of card"]]];

Drawing a large number of lines (CGContextBeginPath) on an iPad

I'm trying to make an ipad application that draws alot, but I really mean alot of lines on stage (10.000+)
using this simple forloop, my ipad crashes after 40~60 seconds (without showing result)
for ( int i = 0; i < 10000; i++ )
{
int r_x = rand() % 750;
int r_y = rand() % 1000;
CGPoint pointpoint = CGPointMake(r_x, r_y);
UIColor *st = [[GetColor alloc] getPixelColorAtLocation:pointpoint];
DrawLine *drawview = [[DrawLine alloc]initWithFrame:CGRectMake(r_x, r_y, 20, 20) selectedcolor:st];
[self.view addSubview:drawview];
[drawview release];
[DrawLine release];
[GetColor release];
}
and this is my "DrawLine" class:
- (id)initWithFrame:(CGRect)frame selectedcolor:colors{
if ((self = [super initWithFrame:frame])) {
selectedcolor_t = colors;
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- (void)drawRect:(CGRect)frame{
CGContextRef c = UIGraphicsGetCurrentContext();
float* colors = CGColorGetComponents(selectedcolor_t.CGColor);
CGContextSetStrokeColor(c, colors);
CGContextBeginPath(c);
CGContextMoveToPoint(c, 0.0f, 0.0f);
CGContextAddLineToPoint(c, 20.0f, 20.0f);
CGContextStrokePath(c);
}
how can I solve this problem? How can I draw this much subviews without crashing the iOS?
thanks so much!! :)
Please reconsider what you are doing there:
In line 4 of your loop, you alloc an instance of GetColor — which you never use again. Ask yourself: Does that make any sense from a design point of view?
In that same line, if you don't violate Cocoa's naming-conventions, you create a UIColor that is never released...
Then in line 8 you release the class-object of DrawLine (ditto that for the next line and the GetColor-class). This is terribly, horribly wrong!
Please visit the Memory Management Programming Guide at the iOS Dev-Center and read the first two sections (again)!
Besides that, re-evaluate your design:
Should GetColor really be a class, so that you create instances? Wouldn't a simple helper-function for color interpolation make more sense in this context?
If it should be a class, why not create just one instance of it outside of the loop and simply query it repeatedly for the colors?
Do you really need a subclass of UIView to draw a single straight, solid, single-colored line? If the lines need not be updated, you should (as Richard and nacho4d suggested) draw all of them in one object (e.g. by a custom UIView or by a delegate of CALayer implementing the drawLayer:inContext: method). If you need to update those lines later, you could simply (ab)use CALayer...
In the latter case, your problem then becomes:
Calculate your random coordinates.
Calculate your color.
Create an opaque CALayer with
a) that color as its backgroundColor,
b) a width of 20 * sqrt(2),
c) a height of whatever-you-want-to-be-the-width-of-that-line,
d) your point as its origin and
e) a rotation of 45.
Add that layer as a sublayer to self.view's layer.
Cheers
Daniel
If your lines are static (not moving later, not animating, etc) , as they seem to be, you could also draw all the lines in a single drawRect: in one view without creating 1000 of CALayers.
I can't tell if this is faster than drawing 1000 CALayers (because CoreAnimation is hardware accelerated and CoreGraphics is not) but it's surely lighter since all the lines will be flattened in a single bitmap. (which is the context of your view)
Just move your for loop inside your drawRect: and follow danyowde advices.( you just need one color object or a helper function but not to create a color each iteration)
Good luck, Hope it helps;)