xcode Sprite Kit Score counts and Coin is removed before Hero touches it - sprite

I am a Newbie, and I am making my first game. Everything is working great accept when I added coins.
-(void)spawnCoin {
SKNode* coinNode = [SKNode node];
coinNode.position = CGPointMake(self.frame.size.width + 150 + (arc4random() % 100), 0 );
coinNode.zPosition = -10;
CGFloat y = arc4random() % (NSInteger)( self.frame.size.height / 2 ) + 40;
SKTexture* coinTexture1 = [SKTexture textureWithImageNamed:#"Coins_1"];
coinTexture1.filteringMode = SKTextureFilteringNearest;
SKTexture* coinTexture2 = [SKTexture textureWithImageNamed:#"Coins_2"];
coinTexture2.filteringMode = SKTextureFilteringNearest;
SKTexture* coinTexture3 = [SKTexture textureWithImageNamed:#"Coins_3"];
coinTexture3.filteringMode = SKTextureFilteringNearest;
SKTexture* coinTexture4 = [SKTexture textureWithImageNamed:#"Coins_4"];
coinTexture4.filteringMode = SKTextureFilteringNearest;
SKTexture* coinTexture5 = [SKTexture textureWithImageNamed:#"Coins_5"];
coinTexture5.filteringMode = SKTextureFilteringNearest;
SKTexture* coinTexture6 = [SKTexture textureWithImageNamed:#"Coins_6"];
coinTexture6.filteringMode = SKTextureFilteringNearest;
SKAction* spin = [SKAction repeatActionForever:[SKAction animateWithTextures:#[coinTexture1, coinTexture2, coinTexture3, coinTexture4, coinTexture5, coinTexture6] timePerFrame:0.05]];
_coin = [SKSpriteNode spriteNodeWithTexture:coinTexture6];
[_coin runAction:spin];
[_coin setScale:1.0];
_coin.position = CGPointMake( 0, y );
_coin.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:_coin.size];
_coin.physicsBody.dynamic = NO;
_coin.physicsBody.categoryBitMask = scoreCategory;
_coin.physicsBody.contactTestBitMask = birdCategory;
[coinNode addChild:_coin];
[coinNode runAction:_moveCoinsAndRemove];
[_coins addChild:coinNode];
SKNode* contactNode = [SKNode node];
contactNode.position = CGPointMake(0,y);
contactNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:_coin.size];
contactNode.physicsBody.dynamic = NO;
contactNode.physicsBody.categoryBitMask = scoreCategory;
contactNode.physicsBody.contactTestBitMask = birdCategory;
[_coin addChild:contactNode];
}
(void)didBeginContact:(SKPhysicsContact *)contact {
if (_score > _heighscore) {
[[NSUserDefaults standardUserDefaults] setInteger:_score forKey:#"HighScoreSave"];
// Vibrate
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
}
if( _moving.speed > 0 ) {
if( ( contact.bodyA.categoryBitMask & scoreCategory ) == scoreCategory || ( contact.bodyB.categoryBitMask & scoreCategory ) == scoreCategory ) {
// contact with score entity
SKNode* coinNode = contact.bodyB.node;
[coinNode removeFromParent];
coinNode.hidden = YES;
_score++;
_scoreLabelNode.text = [NSString stringWithFormat:#"%ld", (long)_score];

Solved this,
coinNode.position = CGPointMake(self.frame.size.width / 1 + _coin.size.width / 1 - 50 + (arc4random() % 50), 0 );
coinNode.zPosition = -10;
CGFloat y = arc4random() % (NSInteger)( self.frame.size.height / 2 ) + 20;
But now I have a NEW problem. When my hero hits the coins they react like obstacles and he is killed instead of just counting and vanishing. It add to to the score for the hit, but also stops the entire game as if the hero has been killed.
Here is my code:
[_coin setScale:1.0];
_coin.position = CGPointMake( 0, y );
_coin.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:_coin.size];
_coin.physicsBody.dynamic = NO;
_coin.physicsBody.usesPreciseCollisionDetection = YES;
_coin.physicsBody.categoryBitMask = coinCategory;
_coin.physicsBody.collisionBitMask = 0;
_coin.physicsBody.contactTestBitMask = birdCategory;
[coinNode addChild:_coin];
SKNode* coinContactNode = [SKNode node];
coinContactNode.position = CGPointMake( _bird.size.width / 0.5, CGRectGetMidY( _coin.frame ) );
coinContactNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(_coin.size.width, _coin.size.height)];
coinContactNode.physicsBody.dynamic = NO;
coinContactNode.physicsBody.usesPreciseCollisionDetection = YES;
coinContactNode.physicsBody.categoryBitMask = coinCategory;
coinContactNode.physicsBody.collisionBitMask = 0;
coinContactNode.physicsBody.contactTestBitMask = birdCategory;
[_coin addChild:coinContactNode];
[coinNode runAction:_moveCoinsAndRemove];
[_coins addChild:coinNode];
And here:
(void)didBeginContact:(SKPhysicsContact *)contact {
if (_score > _heighscore) {
[[NSUserDefaults standardUserDefaults] setInteger:_score forKey:#"HighScoreSave"];
// Sound effect – Score
[self runAction:[SKAction playSoundFileNamed:#"Tap_It_Real_Good.mp3" waitForCompletion:NO]];
// Vibrate
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
}
if( _moving.speed > 0 ) {
if( ( contact.bodyA.categoryBitMask & coinCategory ) == coinCategory || ( contact.bodyB.categoryBitMask & coinCategory ) == coinCategory ) {
_score2++;
_scoreLabelNode2.text = [NSString stringWithFormat:#"%ld", (long)_score2];
// Sound effect – Score
[self runAction:[SKAction playSoundFileNamed:#"Tap_It.mp3" waitForCompletion:NO]];
// Add a little visual feedback for the score increment
[_scoreLabelNode2 runAction:[SKAction sequence:#[[SKAction scaleTo:1.5 duration:0.2], [SKAction scaleTo:1.0 duration:0.2]]]];
}
if( ( contact.bodyA.categoryBitMask & scoreCategory ) == scoreCategory || ( contact.bodyB.categoryBitMask & scoreCategory ) == scoreCategory ) {
// Bird has contact with score entity
_score++;
// Sound effect – Score
[self runAction:[SKAction playSoundFileNamed:#"Tap_It.mp3" waitForCompletion:NO]];
_scoreLabelNode.text = [NSString stringWithFormat:#"%ld", (long)_score];
// Add a little visual feedback for the score increment
[_scoreLabelNode runAction:[SKAction sequence:#[[SKAction scaleTo:1.5 duration:0.2], [SKAction scaleTo:1.0 duration:0.2]]]];
} else {
// Bird has collided with world
_moving.speed = 0;
_bird.physicsBody.collisionBitMask = worldCategory;
_coins.speed = 0;
_bird.speed = 0;
[_bird runAction:[SKAction rotateByAngle:M_PI * _bird.position.y * 0.01 duration:_bird.position.y * 0.003] completion:^{
}];
// Sound effect – Collision
[self runAction:[SKAction playSoundFileNamed:#"Tap_It.mp3" waitForCompletion:NO]];
// Vibrate
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
// Flash background if contact is detected
[self removeActionForKey:#"flash"];
[self runAction:[SKAction sequence:#[[SKAction repeatAction:[SKAction sequence:#[[SKAction runBlock:^{
self.backgroundColor = [SKColor redColor];
}], [SKAction waitForDuration:0.05], [SKAction runBlock:^{
self.backgroundColor = _skyColor;
}], [SKAction waitForDuration:0.05]]] count:4], [SKAction runBlock:^{
_canRestart = YES;
}]]] withKey:#"flash"];
}
}
}
Any help. Thanks :)

Related

Memory leak with CIColor spritekit

I created a class that would generate a hud item, this hud item can animate the resulting texture which is a gradient created using cicolor that is then saved into a uiimage which is in turn used for an sktexture. I've noticed now that i am getting a lot of memory growth in my app and running it through instruments has shown me this, but i can't for the life figure out whats going on:
Here's the error i get
You can't really see the issue so it's giving me 91.4% on this line of code:
animatedGraphic = [[SKSpriteNode alloc]initWithTexture:[[TextureList sharedManager]returnGradientofSize:[[TextureList sharedManager]returnTextureSize:kGMHUDFlowerTarget] topColor:[CIColor colorWithRed:255.0/255.0 green:171.0/255.0 blue:121.0/255.0] bottomColor:[CIColor colorWithRed:225.0/255.0 green:57.0/255.0 blue:86.0/255.0]] color:[UIColor orangeColor] size:CGSizeMake(0, self.frame.size.height)];
animatedGraphic.anchorPoint = CGPointMake(0, 0.5);
animatedGraphic.zPosition = self.zPosition+1;
[self addChild:animatedGraphic];
Heres the code for the sktexture with a gradient:
-(SKTexture*)returnHorizontalGradientofSize:(CGSize)size
leftColor:(CIColor*)leftColor
rightColor:(CIColor*)rightColor{
CIContext *coreImageContext = [CIContext contextWithOptions:nil];
CIFilter *gradientFilter = [CIFilter filterWithName:#"CILinearGradient"];
[gradientFilter setDefaults];
CIVector *startVector = [CIVector vectorWithX:0 Y:size.height/2];
CIVector *endVector = [CIVector vectorWithX:size.width Y:size.height/2];
[gradientFilter setValue:startVector forKey:#"inputPoint0"];
[gradientFilter setValue:endVector forKey:#"inputPoint1"];
[gradientFilter setValue:leftColor forKey:#"inputColor0"];
[gradientFilter setValue:rightColor forKey:#"inputColor1"];
CGImageRef cgimg = [coreImageContext createCGImage:[gradientFilter outputImage]
fromRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *theImage = [UIImage imageWithCGImage:cgimg];
CFRelease(cgimg);
return [SKTexture textureWithImage:theImage];
}
Heres the code for the hud item:
#import "ItemHud.h"
#import "TextureList.h"
#import "UnlockController.h"
#interface ItemHud ()
#property (nonatomic) double scoreIncrement;
#property (nonatomic) double increment;
#property (nonatomic) double barIncrement;
#property (nonatomic) double updateIncrement;
#property (nonatomic) BOOL barAnimating;
#end
#implementation ItemHud
#synthesize theLabel;
#synthesize theLabelTwo;
#synthesize animatedGraphic;
#synthesize iconGraphic;
-(id)initWithImageNamed:(NSString *)ImageName
withLabel:(NSString *)LabelName
withLabelTwo:(NSString *)LabelNameTwo
withIconGraphic:(NSString *)iconGraphicName
withAnimatedGraphic:(BOOL)AnimatedGraphicName{
if (self = [super init]) {
if (ImageName)
{
self.size = [[TextureList sharedManager]returnTextureSize:ImageName];
self.texture = nil;
self.color = [UIColor colorWithRed:0.0/255.0 green:0.0/255.0 blue:0.0/255.0 alpha:0.65];
self.userInteractionEnabled = NO;
_barAnimating = NO;
}
if (AnimatedGraphicName) {
animatedGraphic = [[SKSpriteNode alloc]initWithTexture:[[TextureList sharedManager]returnGradientofSize:[[TextureList sharedManager]returnTextureSize:kGMHUDFlowerTarget] topColor:[CIColor colorWithRed:255.0/255.0 green:171.0/255.0 blue:121.0/255.0] bottomColor:[CIColor colorWithRed:225.0/255.0 green:57.0/255.0 blue:86.0/255.0]] color:[UIColor orangeColor] size:CGSizeMake(0, self.frame.size.height)];
animatedGraphic.anchorPoint = CGPointMake(0, 0.5);
animatedGraphic.zPosition = self.zPosition+1;
[self addChild:animatedGraphic];
}
if (iconGraphicName) {
if ([iconGraphicName isEqualToString:kGMHUDLevelIcon1] || [iconGraphicName isEqualToString:kGMHUDLevelIcon2] || [iconGraphicName isEqualToString:kGMHUDLevelIcon3] || [iconGraphicName isEqualToString:kGMHUDLevelIcon4]|| [iconGraphicName isEqualToString:kGMHUDLevelIcon5] || [iconGraphicName isEqualToString:kGMHUDLevelIcon6] || [iconGraphicName isEqualToString:kGMHUDLevelIcon7] || [iconGraphicName isEqualToString:kGMHUDLevelIcon8] || [iconGraphicName isEqualToString:kGMHUDLevelIcon9]) {
iconGraphic = [[SKSpriteNode alloc]initWithTexture:[SKTexture textureWithImageNamed:iconGraphicName] color:nil size:[[TextureList sharedManager]returnTextureSize:kGMHUDLevelIcon1]];
}
else{
iconGraphic = [[SKSpriteNode alloc]initWithTexture:[SKTexture textureWithImageNamed:iconGraphicName] color:nil size:[[TextureList sharedManager]returnTextureSize:iconGraphicName]];
}
iconGraphic.zPosition = self.zPosition+1;
[self addChild:iconGraphic];
[self setGraphicRight:NO];
}
if (LabelName) {
theLabel = [SKLabelNode labelNodeWithFontNamed:kFontName];
[theLabel setFontColor:[UIColor whiteColor]];
[theLabel setFontName:kFontName];
[theLabel setFontSize:kFontSizeMDMedium];
[theLabel setHorizontalAlignmentMode:SKLabelHorizontalAlignmentModeLeft];
[theLabel setVerticalAlignmentMode:SKLabelVerticalAlignmentModeCenter];
theLabel.text = LabelName;
[self addChild:theLabel];
[self setHudDefaults:YES];
}
if (LabelNameTwo) {
theLabelTwo = [SKLabelNode labelNodeWithFontNamed:kFontName];
[theLabelTwo setFontColor:[UIColor whiteColor]];
[theLabelTwo setFontName:kFontName];
[theLabelTwo setFontSize:kFontSizeMDMedium];
[theLabelTwo setHorizontalAlignmentMode:SKLabelHorizontalAlignmentModeRight];
[theLabelTwo setVerticalAlignmentMode:SKLabelVerticalAlignmentModeCenter];
theLabelTwo.text = LabelNameTwo;
[self addChild:theLabelTwo];
[self setHudDefaults:NO];
}
}
return self;
}
-(void)setBackgroundImage:(SKTexture*)theTexture{
self.texture = theTexture;
}
-(void)setHudDefaults:(BOOL)singleLabel{
theLabelTwo.position = CGPointMake(self.position.x+self.frame.size.width/2,self.position.y);
animatedGraphic.position = CGPointMake(-self.frame.size.width/2,self.position.y);
if (singleLabel) {
[theLabel setHorizontalAlignmentMode:SKLabelHorizontalAlignmentModeCenter];
theLabel.position = CGPointMake(self.position.x,self.position.y);
}
else{
theLabel.position = CGPointMake(theLabelTwo.position.x-theLabelTwo.frame.size.width/2-20,self.position.y);
[theLabel setHorizontalAlignmentMode:SKLabelHorizontalAlignmentModeRight];
}
theLabel.zPosition = self.zPosition+1;
theLabelTwo.zPosition = self.zPosition+1;
}
-(void)setGraphicRight:(BOOL)placeRight{
if (placeRight) {
iconGraphic.position = CGPointMake(self.frame.size.width/2,-self.frame.size.height/4);
iconGraphic.zPosition = animatedGraphic.zPosition+1;
}
else{
iconGraphic.position = CGPointMake(-self.frame.size.width/2,-self.frame.size.height/4);
iconGraphic.zPosition = animatedGraphic.zPosition+1;
}
}
-(void)setBarProgress:(int)flowerTarget currentFlowers:(int)currentFlowers{
double increment = (double)flowerTarget/100;
//NSLog(#"increment is %f",increment);
double barIncrement = (double)self.frame.size.width/100;
//NSLog(#"BAR increment is %f",barIncrement);
double barState = (barIncrement/increment)*currentFlowers;
//NSLog(#"BAR state is %f",barState);
/*if (animatedGraphic.frame.size.width >= self.frame.size.width && !_barAnimating) {
_barAnimating = YES;
[self animateBar:YES];
}
else if (animatedGraphic.frame.size.width < self.frame.size.width && _barAnimating){
_barAnimating = NO;
[self animateBar:NO];
}*/
animatedGraphic.size = CGSizeMake(barState, self.frame.size.height);
}
-(void)setBarValues:(int)startValue increment:(int)increment nextObject:(int)nextObject{
//NSLog(#"0:Totalscore is %i",[[UserDetails sharedManager]userTotalScore]);
//NSLog(#"1:StartValue %i",startValue);
//NSLog(#"2:Increment %i",increment);
//NSLog(#"3:Nextobject %i",nextObject);
_scoreIncrement = (double)startValue/(double)nextObject;
//NSLog(#"increment is %f",increment);
_barIncrement = (double)self.frame.size.width/100;
//NSLog(#"bar increment is %f",barIncrement);
_updateIncrement = ((double)startValue/_scoreIncrement)/100;
//NSLog(#"update increment is %f",updateIncrement);
//NSLog(#"4:Animate %f",_barIncrement/_updateIncrement*increment);
animatedGraphic.size = CGSizeMake(_barIncrement/_updateIncrement*increment, self.frame.size.height);
}
-(void)updateBarProgress:(int)update{
animatedGraphic.size = CGSizeMake(_barIncrement/_updateIncrement*update, self.frame.size.height);
//hudFx.position = CGPointMake(animatedGraphic.frame.size.width-2, animatedGraphic.position.y);
}
-(void)setBarValues:(int)startValue nextObject:(int)nextObject animated:(BOOL)animated{
// start value is difference between unlock score and current value
// next object is score to unlock item
// all unlocks done
if ([[UnlockController sharedManager]allunlocksOpen]) {
theLabel.text = #"ALL ITEMS UNLOCKED";
return;
}
__block int count = 0;
double increment = (double)startValue/(double)nextObject;
//NSLog(#"increment is %f",increment);
double countUp = nextObject-startValue;
//NSLog(#"countup is %f",countUp);
double barIncrement = (double)self.frame.size.width/100;
//NSLog(#"bar increment is %f",barIncrement);
double updateIncrement = ((double)startValue/increment)/100;
//NSLog(#"update increment is %f",updateIncrement);
if (!animated) {
animatedGraphic.size = CGSizeMake(barIncrement/updateIncrement*startValue, self.frame.size.height);
//hudFx.position = CGPointMake(animatedGraphic.frame.size.width-2, animatedGraphic.position.y);
}
else{
SKAction *delay = [SKAction waitForDuration:0.0];
SKAction *animateCount = [SKAction runBlock:^{
count++;
animatedGraphic.size = CGSizeMake(barIncrement*count, self.frame.size.height);
//hudFx.position = CGPointMake(animatedGraphic.frame.size.width-2, animatedGraphic.position.y);
}];
SKAction *animateSequence = [SKAction sequence:#[animateCount,delay]];
SKAction *repeatSequence = [SKAction repeatAction:animateSequence count:(double)countUp/updateIncrement];
[animatedGraphic runAction:repeatSequence completion:^{
}];
}
}
-(void)animateBar:(BOOL)animate{
SKAction *delay = [SKAction waitForDuration:0.15];
SKAction *changeToAnimateBar = [SKAction runBlock:^{
animatedGraphic.texture = [[TextureList sharedManager]returnGradientofSize:[[TextureList sharedManager]returnTextureSize:kGMHUDFlowerTarget] topColor:[CIColor colorWithRed:255.0/255.0 green:244.0/255.0 blue:155.0/255.0] bottomColor:[CIColor colorWithRed:225.0/255.0 green:57.0/255.0 blue:86.0/255.0]];
}];
SKAction *changeToDefaultBar = [SKAction runBlock:^{
animatedGraphic.texture = [[TextureList sharedManager]returnGradientofSize:[[TextureList sharedManager]returnTextureSize:kGMHUDFlowerTarget] topColor:[CIColor colorWithRed:255.0/255.0 green:171.0/255.0 blue:121.0/255.0] bottomColor:[CIColor colorWithRed:225.0/255.0 green:57.0/255.0 blue:86.0/255.0]];
}];
SKAction *animateSequence = [SKAction sequence:#[changeToAnimateBar,delay,changeToDefaultBar,delay]];
SKAction *animatingBarLoop = [SKAction repeatActionForever:animateSequence];
if (animate) {
[self runAction:animatingBarLoop withKey:#"animatingBar"];
}
else{
[self removeActionForKey:#"animatingBar"];
[self runAction:changeToDefaultBar withKey:#"defaultBar"];
}
}
This turned out to be an issue with the AGSpriteButton class which was hogging memory and therefore eventually causing a crash when an advert loaded, you can find a fix here:
SKScene Fails to deallocate memory resulting in bounded memory growth

Programmatically showing new window/view when selecting UICollectionViewCell

My code right now for didSelectItemAtIndexPath is the following:
- (void)collectionView:(AFIndexedCollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
if(collectionView.index == 0){
NSLog(#"Reordenador contenido por columna %li",indexPath.item);
self.my_data = [self.my_data sortByColumn:indexPath.item skip:1 areAllNumbers:TRUE];
[self.tableView reloadData];
}else{
//show a new window with the content of the cell in a Text Field
NSLog(#"Row = %li; Column = %li - content = %#",collectionView.index,indexPath.item,[self.my_data objectInRow:collectionView.index column:indexPath.item]);
}
}
my_data = custom 2D array class object
How would I programmatically open a new popup window / new view with the content of the selected cell inside, for example, a Text Field, and 2 buttons - Save / Cancel?
Fixed with the following coding:
UIView *mySubView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
[mySubView setBackgroundColor:[UIColor blackColor]];
mySubView.tag = TFIELDSUBVIEW_TAG;
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(2, 10, 300, 80)];
self.textField.borderStyle = UITextBorderStyleRoundedRect;
self.textField.font = [UIFont systemFontOfSize:12];
self.textField.placeholder = [self.the_matrix objectInRow:collectionView.index column:indexPath.item];
self.textField.autocorrectionType = UITextAutocorrectionTypeNo;
self.textField.keyboardType = UIKeyboardTypeDefault;
self.textField.returnKeyType = UIReturnKeyDone;
self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
self.textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
self.textField.textAlignment = NSTextAlignmentCenter;
self.textFieldColumn = indexPath.item;
self.textFieldRow = collectionView.index;
UIButton *buttonOK = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonOK.tag = TFIELDSUBVIEW_TAG;
[buttonOK setBackgroundImage:[UIImage imageNamed:#"ok.jpg"] forState:UIControlStateNormal];
[buttonOK addTarget:self
action:#selector(okClicked)
forControlEvents:UIControlEventTouchUpInside];
[buttonOK setTitle:#"" forState:UIControlStateNormal];
buttonOK.backgroundColor = [UIColor grayColor];
buttonOK.frame = CGRectMake(50, 100, 50, 30);
buttonOK.tintColor = [UIColor greenColor];
UIButton *buttonCANCEL = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonCANCEL.tag = TFIELDSUBVIEW_TAG;
[buttonCANCEL addTarget:self
action:#selector(cancelClicked)
forControlEvents:UIControlEventTouchUpInside];
[buttonCANCEL setBackgroundImage:[UIImage imageNamed:#"cancel.jpg"] forState:UIControlStateNormal];
[buttonCANCEL setTitle:#"" forState:UIControlStateNormal];
buttonCANCEL.backgroundColor = [UIColor grayColor];
buttonCANCEL.frame = CGRectMake(120, 100, 75, 30);
buttonCANCEL.tintColor = [UIColor redColor];
[mySubView addSubview:buttonOK];
[mySubView addSubview:buttonCANCEL];
[mySubView addSubview:self.textField];
[self setCustomView:mySubView];
[self.view reloadInputViews];
setCustomView being the following:
-(void) setCustomView:(UIView *)customView {
NSUInteger z = NSNotFound;
if (_customView) {
z = [self.view.subviews indexOfObject:_customView];
}
if (z == NSNotFound) {
[self.view addSubview:customView];
} else {
UIView *superview = _customView.superview;
[_customView removeFromSuperview];
[superview insertSubview:customView atIndex:z];
}
_customView = customView;
}

Sprite Kit NSArray of multiple sprites?

I have 6 sprite images I am trying to add to my scene, adding each of them seems to slow everything down a lot. I figured I would need to create an NSArray in order to help with speed. Here is the array I've created, but it's only adding the first image, how can I get it to add all 6?? Thank you in advance!
myArray
NSArray *myArray = [NSArray arrayWithObjects:#"image1",#"image2",#"image3",#"image4",#"image5",#"image6", nil];
NSInteger count = [myArray count];
for (int i = 0; i < count; i++) {
if (i > 5) {
break;
}
result = [myArray objectAtIndex:i];
}
//Setting SKSpriteNodes from array.
dice = [SKSpriteNode spriteNodeWithImageNamed:[myArray objectAtIndex:result.intValue]];
Define a property in you scene:
#interface MyScene
#property (nonatomic) NSMutableArray *items;
#end
Then create a method to fill that array:
- (void)fillItems {
for (int i=0; i<10; i++) {
SKSpriteNode *d1 = [SKSpriteNode spriteNodeWithImageNamed:#"Sprite1"];
d1.position = CGPointMake(self.frame.size.width/4 + arc4random() % ((int)self.frame.size.width/2),
self.frame.size.height/2 + arc4random() % ((int)self.frame.size.height/2));
d1.color = [self randomColor];
d1.colorBlendFactor = 1.0;
d1.xScale = 0.25;
d1.yScale = 0.25;
d1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:d1.frame.size];
//Adding SpriteKit physicsBody for collision detection
d1.physicsBody.categoryBitMask = diceCategory;
d1.physicsBody.dynamic = YES;
d1.physicsBody.contactTestBitMask = frameCategory;
d1.physicsBody.collisionBitMask = diceCategory | frameCategory;
d1.physicsBody.usesPreciseCollisionDetection = YES;
d1.name = #"Sprite1";
[self.items addObject:d1];
[self addChild:d1];
}

Xcode :How can I stop video in webview and still using webview

if I use
-(void)viewWillDisappear:(BOOL)animated
{
[subView loadHTMLString:nil baseURL:nil];
}
my Webview can't worked
I try to do this
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
[subView loadHTMLString:nil baseURL:nil];
}
I just want to go next page with paging scrollview and stop video on next page
this my code scrollview paging
book = [[NSMutableArray alloc] initWithObjects:#"page11",#"page12",#"page13",#"page14",#"page15", nil];
for (int i = 0; i < [book count]; i++) {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.height * i;
frame.origin.y = 0;
frame.size = CGSizeMake(1024,768);
subView = [[UIWebView alloc] initWithFrame:frame];
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[book objectAtIndex:i] ofType:#"html" inDirectory:#""]];
[subView loadRequest:[NSURLRequest requestWithURL:url]];
subView.scalesPageToFit = YES;
[scrollView setBounces:NO];
[scrollView addSubview:subView];
}
scrollView.contentSize = CGSizeMake(1024 * [book count], 768);
[scrollView setFrame:CGRectMake(0, 0, 1024, 768)];
Can I play video and stop on I next page? //Please advice
sorry my English isn't well
You need to load a blank page into the UIWebView to stop the audio:
[self.webView loadRequest:NSURLRequestFromString(#"about:blank")];
or
[self.webView loadHTMLString:#"" baseURL:nil];
Thank for Advice. I try this is works for me
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
for(int i = 0; i < _pageAmount ; i++){
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
[_collectionView cellForItemAtIndexPath:indexPath].backgroundColor = [UIColor clearColor];
}
currentPage = page;
if (currentPage > 0 && currentPage < [book count]-1) {
[[self.scrollView.subviews objectAtIndex:currentPage-1]reload];//
[[self.scrollView.subviews objectAtIndex:currentPage+1]reload];
}
if(self.interfaceOrientation == 1 || self.interfaceOrientation == 2){
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:page inSection:0];
[_collectionView cellForItemAtIndexPath:indexPath].backgroundColor = [UIColor redColor];
}
}

cocos2d box2d scale sprite -> removechild (how?)

I am little slow in English, please do understand.
Here is my source code:
- (void)createBall:(CGPoint)touchedAt{
CGSize winSize = [CCDirector sharedDirector].winSize;
ball2 = [CCSprite spriteWithFile:#"Ball.png" rect:CGRectMake(0, 0, 54, 54)];
ball2.position = ccp(touchedAt.x,touchedAt.y);
[self addChild:ball2];
b2BodyDef ballBodyDef2;
ballBodyDef2.type = b2_dynamicBody;
ballBodyDef2.position.Set(touchedAt.x/PTM_RATIO, touchedAt.y/PTM_RATIO);
ballBodyDef2.userData = ball2;
b2Body *body2 = _world->CreateBody(&ballBodyDef2);
b2CircleShape circle;
circle.m_radius = 89.0/PTM_RATIO;//(arc4random()*26.0)/PTM_RATIO;
b2FixtureDef ballShapeDef2;
ballShapeDef2.shape = &circle;
ballShapeDef2.density = 1.0f;
ballShapeDef2.friction = 0.2f;
ballShapeDef2.restitution = 0.8f;
body2->CreateFixture(&ballShapeDef2);
}
-(void)createBall2
{
CGSize winSize = [CCDirector sharedDirector].winSize;
globalSprite = [CCSprite spriteWithFile:#"Ball.png"];
globalSprite.position = ccp(winSize.width/2 + globalSprite.contentSize.width, winSize.height/2);
[self addChild:globalSprite];
b2BodyDef ballBodyDef3;
ballBodyDef3.type = b2_dynamicBody;
ballBodyDef3.position.Set(100/PTM_RATIO, 100/PTM_RATIO);
ballBodyDef3.userData = globalSprite ;
b2Body *body3 = _world->CreateBody(&ballBodyDef3);
b2CircleShape circle;
circle.m_radius = 26.0/PTM_RATIO;//(arc4random()*26.0)/PTM_RATIO;
b2FixtureDef ballShapeDef3;
ballShapeDef3.shape = &circle;
ballShapeDef3.density = 1.0f;
ballShapeDef3.friction = 0.2f;
ballShapeDef3.restitution = 0.8f;
body3->CreateFixture(&ballShapeDef3);
}
// initialize your instance here
-(id) init
{
if( (self=[super init])) {
// enable touch
// enable accelerometer
CGSize winSize = [CCDirector sharedDirector].winSize;
self.isAccelerometerEnabled = YES;
self.isTouchEnabled = YES;
// Create sprite and add it to the layer
// Create a world
b2Vec2 gravity = b2Vec2(0.0f, 0.0f);
bool doSleep = true;
_world = new b2World(gravity, doSleep);
// Create edges around the entire screen
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0,0);
b2Body *groundBody = _world->CreateBody(&groundBodyDef);
b2PolygonShape groundBox;
b2FixtureDef boxShapeDef;
boxShapeDef.shape = &groundBox;
groundBox.SetAsEdge(b2Vec2(0,0), b2Vec2(winSize.width/PTM_RATIO, 0));
groundBody->CreateFixture(&boxShapeDef);
groundBox.SetAsEdge(b2Vec2(0,0), b2Vec2(0, winSize.height/PTM_RATIO));
groundBody->CreateFixture(&boxShapeDef);
groundBox.SetAsEdge(b2Vec2(0, winSize.height/PTM_RATIO), b2Vec2(winSize.width/PTM_RATIO, winSize.height/PTM_RATIO));
groundBody->CreateFixture(&boxShapeDef);
groundBox.SetAsEdge(b2Vec2(winSize.width/PTM_RATIO, winSize.height/PTM_RATIO), b2Vec2(winSize.width/PTM_RATIO, 0));
groundBody->CreateFixture(&boxShapeDef);
// Create ball body and shape
[self schedule:#selector(tick:)];
//[self schedule:#selector(gameLogic:) interval:1.0];
[self createBall2];
}
return self;
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
// Choose one of the touches to work with
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
[self createBall:location];
}
- (void)tick:(ccTime) dt {
_world->Step(dt, 10, 10);
for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) {
if (b->GetUserData() != NULL) {
CCSprite *ballData = (CCSprite *)b->GetUserData();
ballData.position = ccp(b->GetPosition().x * PTM_RATIO,
b->GetPosition().y * PTM_RATIO);
ballData.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
}
}
}
I want to
touch -> sprite create(circle) -> sprite scale -> sprite remove
but
- (void)tick:(ccTime) dt <---------- this is simulator turn off!
I want to way
Try this :
world->DestroyBody(sprite);

Resources