Image replacement in iphone - iphone

I have added some sprite by using the following code and then by checking the rect
intersection I want to replace these sprites with another one.Can you help me out by providing code
to replace these random images.Problem is that the image to be replaced is also taken
randomly.........
yp = 40;
//CCSprite *spr;
movableSprites = [[NSMutableArray alloc] init];
for(int m=0; m<4; m++)
{
do
{
i = 'a';
//NSLog(#"valueeeeeeeee %d",i);
next = arc4random()%maxalphabets;
//NSLog(#"valueeeeeeeeenexttttt %d",next);
i+=next;
//NSLog(#"valueeeeeeeee %d",i);
spr = (CCSprite*)[self getChildByTag:i];//checks if found alreadyyyyyy
NSLog(#"Strrrrrrrr is:%#",spr);
}while(spr);
spNameStr = [NSString stringWithFormat:#"%c3.png",i];
NSLog(#"tagggg %d",i);
NSLog(#"spNameStr is:%#",spNameStr);
spr = [CCSprite spriteWithFile:spNameStr ];
spr.tag = i;
//NSLog(#"tagiiiiii %d",i);
spr.position = ccp(60,yp);
[self addChild:spr z:2];
[movableSprites addObject:spr];
yp+=spr.contentSize.height+35;
}
yp = 40;
NSMutableArray *answerimagesCopy = [NSMutableArray arrayWithArray:movableSprites];
NSLog(#"answer image copy elements areeeee %#",answerimagesCopy);
for(k = 0; k < movableSprites.count; ++k)
{
NSLog(#"inside forrrr");
int j=arc4random()%([answerimagesCopy count]);
NSLog(#"valueee of jjjjjjjj %d",j);
CCSprite *ansimage = [answerimagesCopy objectAtIndex:j];
//NSLog(#"................ %#",ansimage);
p=ansimage.tag;
NSLog(#"tagg..... %d",p);
[answerimagesCopy removeObjectAtIndex:j];
//NSLog(#"tagg..... %d",j);
spNameStr = [NSString stringWithFormat:#"%c4.png",p];
NSLog(#"spNameStr is:%#",spNameStr);
//NSLog(#"tagggg %d",j);
spr = [CCSprite spriteWithFile:spNameStr ];
spr.tag = p+100;
spr.position = ccp(260,yp);
[self addChild:spr z:1];
yp+=spr.contentSize.height+35;
}

I have did this using sprite sheet. if you can create a sprite sheet and then assign that sprite sheet to CCSpriteBatchNode's object like
$ CCSpriteBatchNod * m_meteoritesSprites =[CCSpriteBatchNode batchNodeWithFile:#"Meteo.pvr.ccz"];
and then load plist
$[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"Meteo.plist"];
and then use sprite frames to assign images to your sprite like
$ m_meteoritesSprites =[CCSpriteBatchNode batchNodeWithFile:#"Meteo.pvr.ccz"];
i used TexrturePacker to make sprite sheets
hope this helps you.

Related

making my own tile system cause lag

- (void) loadStartingTiles //16 by 24
{
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:
#"clonespritesheet.plist"];
for(int x = 0; x < 16; x++) //minus 1 for one at the begining
{
for(int y = 0; y < 26; y++)
{
CCSprite *tempsprite;
switch (currentscreen[x][y])
{
case 0:
tempsprite = [CCSprite spriteWithSpriteFrameName:#"block0.png"];
break;
case 1:
tempsprite = [CCSprite spriteWithSpriteFrameName:#"block1.png"];
break;
}
tempsprite.position = ccp(y*20+10,(16-x)*20-10); //+10 for align for tile size
[self addChild:tempsprite z:3];
[tiles addObject:tempsprite];
}
}
}
So I make a bunch of sprites from an int array that tells them where they should be then i add them into the nsmutable array tile. then i move everything in the array to the left slowly, and im losing around 20 FPS. what is a more efficient way to make a tile system? my goal is to make randomly generated tiles later on.
- (void) manageTiles:(CGFloat)dt
{
int tileamount = [tiles count];
for(int i = 0; i < tileamount; i++)
{
CCSprite *tempsprite = [tiles objectAtIndex:i];
tempsprite.position = ccp(tempsprite.position.x-20*dt,tempsprite.position.y);
}
}
EDIT: the awnser is
int themap = -20;
- (void) manageTiles:(CGFloat)dt
{
tiles.position = ccp(tiles.position.x-10*dt,tiles.position.y);
NSLog(#"%d",themap);
if(tiles.position.x < themap)
{
CCSprite *tempsprite;
for(int i = 0; i < 16; i++)
{
[tiles removeChildAtIndex:0 cleanup:YES];
}
for(int i = 0; i < 16; i++)
{
switch (tilewall[i])
{
case 0:
tempsprite = [CCSprite spriteWithSpriteFrameName:#"block1.png"];
break;
case 1:
tempsprite = [CCSprite spriteWithSpriteFrameName:#"block1.png"];
break;
}
tempsprite.position = ccp((themap*-1)+500+10,((16-i)*20-10));
[tiles addChild:tempsprite];
}
themap = themap-20;
}
}
Where you are going wrong is, you are not using a CCSpriteBatchNode. A CCSpriteBatchNode will draw all of the tiles in one draw operation instead of doing one draw operation per tile. The drawbacks are, each tile in the batch node will have the same zOrder (in a way), and it all must use one source spritesheet per batch node. SO basically if you wanted different layers at different zOrders, or different layers which use different source images for the tiles, you would have to create multiple batch nodes, one for each.
http://www.cocos2d-iphone.org/api-ref/0.99.5/interface_c_c_sprite_batch_node.html
Preload the tempsprite variable outside your loop:
CSprite *sprite0 = [CCSprite spriteWithSpriteFrameName:#"block0.png"];
CSprite *sprite1 = [CCSprite spriteWithSpriteFrameName:#"block1.png"];
And then refer them to them in the loop:
switch (currentscreen[x][y])
{
case 0:
tempsprite = sprite0;
break;
case 1:
tempsprite = sprite1;
break;
}
or even better:
tempsprite = currentscreen[x][y] ? sprite1 : sprite0;
Oh, and your inner loop should refer to 24, not 26.

Sprites are disappear after some time

Here some code for Add sprite for Enemies.....
_robbers = [[CCArray alloc] initWithCapacity:kNumAstroids];
for (int i = 0; i < kNumAstroids; ++i) {
CCSprite *asteroid = [CCSprite spriteWithSpriteFrameName:#"robber.png"];
asteroid.visible = NO;
[_batchNode addChild:asteroid];
[_robbers addObject:asteroid];
}
And in Update method ........
double curTime = CACurrentMediaTime();
if (curTime > _nextRunemanSpawn) {
float randSecs = [self randomValueBetween:0.20 andValue:1.0];
_nextRunemanSpawn = randSecs + curTime;
float randY = [self randomValueBetween:80 andValue:80];
float randDuration = [self randomValueBetween:4.5 andValue:4.5];
float randDuration1 = [self randomValueBetween:1.0 andValue:1.0];
CCSprite *asteroid = [_robbers objectAtIndex:_nextRobber];
_nextRobber++;
if (_nextRobber >= _robbers.count) {
_nextRobber = 1;
}
[asteroid stopAllActions];
asteroid.position = ccp(winSize.width +asteroid.contentSize.width / 2 , randY);
asteroid.visible = YES;
[asteroid runAction:[CCSequence actions:[CCMoveBy actionWithDuration:randDuration position:ccp(-winSize.width-asteroid.contentSize.width, 0)],
[CCCallFuncN actionWithTarget:self selector:#selector(setInvisible:)],nil]];
All Sprites are Move from right to left in screen
when Sprite crosses the middle of the screen it automatically disappear
what is the reason for this problem ??
I agree with the previously mentioned statement from LearnCocos2D. It is also possible that you are adding multiple objects and reaching the end of the capacity in the line
_robbers = [[CCArray alloc] initWithCapacity:kNumAstroids];
If you try to spawn more objects than whatever number you have specified for kNumAsteroids it will remove the oldest object and use the new one in its place. I.e. if kNumAsteroids is 5, you have 5 on the screen and then add a sixth, 1 will become 6 and its position will be whatever you set it to.

iPhone:How can I shuffle buttons in view

I have many no. of buttons on my view and I want to shuffle the buttons(change in position) then how can I shuffle the button in my view.
use arc4random()
and change position of your buttons
In your .h file : UIButton *buttonsarray[10];
In your .m file :
// Make array of button using following way.I used this method to creates button and you can use yours.
- (void)viewDidLoad {
[super viewDidLoad];
float y = 5;
int x = 0;
int count = 0;
for (int i = 0 ; i < 10; i++)
{
count ++;
buttonsarray[i] = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonsarray[i].frame = CGRectMake(x, y, 100, 100);
[buttonsarray[i] setTitle:[NSString stringWithFormat:#"%d",i+1] forState:UIControlStateNormal];
x = x + 105;
[self.view addSubview:b[i]];
if(count == 3)
{
count = 0;
x = 0;
y = y+ 105;
}
}
}
// This function will soufflé your buttons
- (IBAction)btnClicked:(id)sender
{
int n = 10;
int swaper;
for (int i = 0 ; i < 10 ; i++)
{
int r = arc4random()%n;
if(r != swaper){
swaper = r;
CGRect r1 = buttonsarray[i].frame;
buttonsarray[i].frame = buttonsarray[swaper].frame;
buttonsarray[swaper].frame = r1;
n--;
}
}
}
Hope,this will help you..
You can do this
Make an Array with a group of CGPoints you will need to store the points as strings.
In the layoutSubViews method set something like this:
-(void)layoutSubViews{
[self.subviews enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
CGPoint newPoint = CGPointFromString([positionsArray objectAtIndex:idx]);
object.frame = CGRectMake(newPoint.x,newPoint.y,object.frame.size.width,object.frame.size.height);
}];
}
Then you will need to shuffle the positions in the positions array, you can see an example method here :How to Shuffle an Array
Now every time you need to Shuffle the positions you can call -(void)setNeedsLayout on your view.
There are more options but that was the first I thought of.
Good Luck

Cocos2D: CCParallaxNode doesn't display until I move my map a bit

I'm using Cocos2D 0.99.5. I have a CCParallaxNode with background sprites added to it. For some reason, none of them display until I start my map starts moving around a bit. The scroll slowly with the players movement.
I have this added to init:
winSize = [CCDirector sharedDirector].winSize;
bgMountainsMax = floor(winSize.width/240)+1;
if((int)winSize.width%240 > 0){
bgMountainsBumper = ((int)winSize.width%240)/bgMountainsMax;
}else{
bgMountainsBumper = 0;
}
backgroundNode = [CCParallaxNode node];
[self addChild:backgroundNode z:-1];
CGPoint mountainSpeed = ccp(0.5, 0.5);
bgMountains = [[NSMutableArray alloc] initWithCapacity: bgMountainsMax];
for(int i=0; i<bgMountainsMax; ++i){
mountain = [CCSprite spriteWithFile:#"mountainBG1.png"];
mountain.opacity = 80;
[bgMountains insertObject:mountain atIndex:i];
[backgroundNode addChild:[bgMountains objectAtIndex:i] z:0 parallaxRatio:mountainSpeed positionOffset:ccp((240*i)+(bgMountainsBumper*i),98)];
}
And this added to update:
for (CCSprite *mountainNum in bgMountains) {
if ([backgroundNode convertToWorldSpace:mountainNum.position].x < -(240/2)) {
[backgroundNode incrementOffset:ccp(winSize.width+(240),0) forChild:mountainNum];
}
if ([backgroundNode convertToWorldSpace:mountainNum.position].x > winSize.width+(240/2)) {
[backgroundNode incrementOffset:ccp(-(winSize.width+240),0) forChild:mountainNum];
}
}
I think you should be calling the update function stuff once at the end of your init stuff
[backgroundNode incrementOffset:ccp(winSize.width+(240),0) forChild:mountainNum];
[backgroundNode incrementOffset:ccp(-(winSize.width+240),0) forChild:mountainNum];
without the conditionals, to set it up initially.

removing integers from an array

I need to make an array for the co ordinates of my sprites and i wanted to remove the co-ordinate once the sprite has that co-ordinate from the array as i don't want another sprite having the same co-ordinate, i can't seem to get it to work, there are no errors and when debugging it says nsexception and quits. what am i doing wrong and where do i deallocate the arrays? when i release them in dealloc it says i need to declare them.
CGPoint cg1 = CGPointMake(33,33);
NSValue *cg1obj = [NSValue valueWithCGPoint:cg1];
CGPoint cg2 = CGPointMake(33,97);
NSValue *cg2obj = [NSValue valueWithCGPoint:cg2];
NSMutableArray *numberxy = [[NSMutableArray alloc] init]; int pointcount = 0;
[numberxy insertObject:cg1obj atIndex:pointcount++];
[numberxy insertObject:cg2obj atIndex:pointcount++];
NSMutableArray *sprites = [[NSMutableArray alloc] init]; int spritecount = 0;
[sprites insertObject:red1 atIndex:spritecount++];
[sprites insertObject:red2 atIndex:spritecount++];
for (int i=0; i<3;i++) {
int rpoint = arc4random() % 3;
int rsprite = arc4random() % 3;
CGPoint point = [[numberxy objectAtIndex:rpoint] CGPointValue];
CCSprite *sprite1 = [sprites objectAtIndex:rsprite];
sprite1.position = ccp(point.x,point.y);
if (sprite1.position.x == point.x && sprite1.position.y == point.y) {
[numberxy removeObjectAtIndex:rpoint];
[sprites removeObjectAtIndex:rsprite];
}
}
Your code is weird. Why is xValue defined after it is used? You may have a leak if xValue was defined previously in the same manner and now you are redefining xValue. You then check if X is in the new xValue. There is nothing in the new xValue so the if statement will evaluate to false, so nothing will be removed.
NSNumber *X = [NSNumber numberWithInt:randomNumberx];
[xValue containsObject: numberx];
xValue = [[NSMutableArray alloc]init];
if ([xValue containsObject:X]) {
[numberx removeObject:X];
}
Also what is the point of [xValue containsObject: numberx]; outside of the if statement? It doesn't have a purpose.