using cocos2d to design shootgame, i can't invoke stopGame method - objective-c

-(void)spriteMoveFinishedid)sender //when sprite is outside of screen,it's deleted;
{
CCSprite *sprite = (CCSprite *)sender;
if (sprite.tag == 1) //it's enemy;
{
escapeNum++;
[self removeChild:sprite cleanup:YES];
if (escapeNum == 10)
{
[self stopGameEx]; //Because the speed of every enemy isn't same to other and there are bullets,it maybe happens that two sprites disappear at the same time, and the program stop at this with error --- program received signal:“EXC_BAD_ACCESS”。
}
//...........
}
}
How to resolve it?

Inside if loop, change sprite tag to mark it as expired sprite, and some where else remove.
enum
{
kTagExpiredSprite = 999 //any number not ur sprite tag(1)
};
.....
-(void)spriteMoveFinishedid)sender //when sprite is outside of screen,it's deleted;
{
CCSprite *sprite = (CCSprite *)sender;
if (sprite.tag == 1) //it's enemy;
{
escapeNum++;
sprite.tag = kTagExpiredSprite;
if (escapeNum == 10)
{
[self stopGameEx]; //Because the speed of every enemy isn't same to other and there are bullets,it maybe happens that two sprites disappear at the same time, and the program stop at this with error --- program received signal:“EXC_BAD_ACCESS”。
}
//...........
}
}

Related

SpriteKit - Using a loop to create multiple sprites. How do I give each sprite a different variable name?

I am using SpriteKit.
The code below basically makes a lattice of dots on the screen. However, I want to call each 'dot' a different name based on its position, so that I can access each dot individually in another method. I'm struggling a little on this, so would really appreciate if someone could point me in the right direction.
#define kRowCount 8
#define kColCount 6
#define kDotGridSpacing CGSizeMake (50,-50)
#import "BBMyScene.h"
#implementation BBMyScene
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
/* Setup your scene here */
// Background
self.backgroundColor = [SKColor colorWithRed:0.957 green:0.957 blue:0.957 alpha:1]; /*#f4f4f4*/
CGPoint baseOrigin = CGPointMake(35, 385);
for (NSUInteger row = 0; row < kRowCount; ++row) {
CGPoint dotPosition = CGPointMake(baseOrigin.x, row * (kDotGridSpacing.height) + baseOrigin.y);
for (NSUInteger col = 0; col < kColCount; ++col) {
SKSpriteNode *dot = [SKSpriteNode spriteNodeWithImageNamed:#"dot"];
dot.position = dotPosition;
[self addChild:dot];
//6
dotPosition.x += kDotGridSpacing.width;
}
}
}
return self;
}
Here is an image of what appears on screen when I run the above code...
http://cl.ly/image/3q2j3E0p1S1h/Image1.jpg
I simply want to be able to call an individual dot to do something when there is some form of user interaction, and I'm not sure how I would do that without each dot having a different name.
If anyone could help I would really appreciate it.
Thanks,
Ben
- (void)update:(NSTimeInterval)currentTime {
for(SKNode *node in self.children){
if ([node.name containsString:#"sampleNodeName"]) {
[node removeFromParent];
}
}
}
Hope this one helps!
You can set the name property of each node inside the loop.
Then you can access them with self.children[index].
If you want to find a specific node in your children, you have to enumerate through the array.
Update:
To clarify how to search for an item by iterating, here is a helper method:
- (SKNode *)findNodeNamed:(NSString *)nodeName
{
SKNode *nodeToFind = nil;
for(SKNode *node in self.children){
if([node.name isEqualToString:nodeName]){
nodeToFind = node;
break;
}
}];
return nodeToFind;
}

For loop in Sprite Kit seems to be emptying an array?

I'm just starting to wrap my brain around Sprite Kit and I am encountering a very strange error when attempting to change the property of a node in a for loop im using.
I have two SKSpriteNode objects, one is the child of a SKScene (BLATheBugs) and the other is a child of the first (BLAEmptySpaces). I have a grid laid out with BLAEmptySpaces, and BLATheBugs on top of those empty spaces which are supposed to take UITouch, and move to an empty space if its bool isOccpupied property == False. When the scene is set up, the SKScene triggers a method in TheBugs:
-(void) spawnEmptySpacesInitialize
{
[self addChild:[self spawnEmptySpaces]];
}
which in turn triggers:
-(BLAEmptySpaces *) spawnEmptySpaces
{
emptySpace = [[BLAEmptySpaces alloc] init];
emptySpace.numberOfEmptySpacesNeeded = 12;
[emptySpace spawnEmptySpaces];
[emptySpace positionTheEmptySpaces];
return emptySpace;
}
which finally triggers a method in the EmptySpaces object:
-(BLAEmptySpaces *) spawnEmptySpaces
{
_emptySpacesArray = [NSMutableArray new];
for (int x = 0; x < _numberOfEmptySpacesNeeded; x++)
{
_anEmptySpace = [[BLAEmptySpaces alloc] initWithImageNamed:#"BlueLight.png"];
_anEmptySpace.zPosition = 50;
[_emptySpacesArray addObject:_anEmptySpace];
[self addChild: _anEmptySpace];
}
return self;
}
everything seems fine, (except for needing the additional "addChild" in the EmptySpaces object to get them to be drawn on the screen which i have also been trying to fix) but when i call the method to move TheBugs:
-(void) moveLeftOneSpace
{
NSLog(#"%d", emptySpace.emptySpacesArray.count);
for (emptySpace in emptySpace.emptySpacesArray)
{
NSLog(#"cycle");
if (emptySpace.isOccupied == NO)
{
for (_yellowBug in yellowBugArray)
{
if (_positionOfFingerTouchX > _yellowBug.position.x - variableOne && _positionOfFingerTouchX < _yellowBug.position.x + variableTwo && _positionOfFingerTouchY > _yellowBug.position.y - variableOne && _positionOfFingerTouchY < _yellowBug.position.y + variableTwo && emptySpace.position.x == _yellowBug.position.x - 80 && emptySpace.position.y == _yellowBug.position.y)
{
_yellowBug.position = CGPointMake(_yellowBug.position.x - spaceBetweenBugs, _yellowBug.position.y);
emptySpace.isOccupied = YES;
NSLog(#"execute");
}
}
}
}
}
It at first tells me there are 12 objects in the array and runs the operation. if I try to move any piece again, it tells me there are now NO objects in the array (yellowBugArray). It is also probably worth noting that it will not let me access emptySpace.anEmptySpace. Throws me an error.
Sorry for the long post, but hopefully somewhere in here is the cause of my problem.
Thank you very much guys!

Getting two images to appear in random sequence iOS

I am new to the community, so let me know if my question is unclear. I am trying to make a choice reaction exercise on the iPAD. There are two images that should appear in random sequence on the left and right of the screen, and the user will respond by tapping a button that corresponds to the position of the appeared image. Here's the problem, I tried to get the two images to appear at random order using the following way:
- (void) viewDidAppear:(BOOL)animated
{
for(int n = 1; n <= 20; n = n + 1)
{
int r = arc4random() % 2;
NSLog(#"%i", r);
if(r==1)
{
[self greenCircleAppear:nil finished:nil context: nil];
}
else
{
[self redCircleAppear:nil finished:nil context: nil];
}
}
}
However, 20 random numbers get generated while only 1 set of animation is run. Is there a way to let the animation finish running in each loop before the next loop begins? Any help is appreciated, thanks in advance!
When you say "only one set of animation is run" I'm assuming that means greenCircleAppear and redCircleAppear begin the sequence of images appearing and the user pressing a button. If that's the case, I'd recommend not using a for loop in viewDidAppear but instead have viewDidAppear initialize the current state and call a method that presents the next animation. When the animation is finished, have it call the method that presents the next animation. Something along these lines:
Add this to the interface:
#interface ViewController ()
#property NSInteger currentIteration;
#end
This is in the implementation:
- (void)viewDidAppear:(BOOL)animated {
self.currentIteration = 0;
[self showNextAnimation];
}
- (void)greenCircleAppear:(id)arg1 finished:(id)arg2 context:(id)arg3 {
//perform animation
NSLog(#"green");
[self showNextAnimation];
}
- (void)redCircleAppear:(id)arg1 finished:(id)arg2 context:(id)arg3 {
//perform animation
NSLog(#"red");
[self showNextAnimation];
}
- (void)showNextAnimation {
self.currentIteration = self.currentIteration + 1;
if (self.currentIteration <= 20) { //you should replace '20' with a constant
int r = arc4random() % 2;
NSLog(#"%i", r);
if(r==1)
{
[self greenCircleAppear:nil finished:nil context: nil];
}
else
{
[self redCircleAppear:nil finished:nil context: nil];
}
}
else {
//do what needs to be done after the last animation
}
}

Deleting one object at a time every 5 seconds Cocos2d

I have a problem with my cocos2d game. I am trying to delete a projectile shot by an enemy every 5 seconds (each projectile is supposed to have a lifetime of 5 seconds), but I cannot figure out how to do it. I get the error of
Assertion failure in -[CCTimer initWithTarget:selector:interval:]
Here is my code:
-(void)projectileShooting:(ccTime)dt
{
[self schedule:#selector(projectileShooting:) interval:2.5];
projcount++;
if([proj count] <= 15 ){
if(enemy1.position.y < 320){
v = ccp(player.position.x,player.position.y);
for(CCSprite *enemies in enemy){
CCSprite * projectilebullet = [CCSprite spriteWithFile:#"Projectile.png"];
[proj addObject:projectilebullet];
[self addChild:projectilebullet];
CGPoint MyVector = ccpSub(enemies.position,player.position );
MyVector = ccpNormalize(MyVector);
MyVector = ccpMult(MyVector, enemies.contentSize.width/2);
MyVector = ccpMult(MyVector,-1);
projectilebullet.position = ccpAdd(enemies.position, MyVector);
for(CCSprite *projectile in proj){
[self schedule:#selector (deleteprojectile:projectile:) interval:5];
}
}
}
}
for(CCSprite *enem2 in enemytwo)
{
if( [proj count] <= 15){
CCSprite * projectilebull = [CCSprite spriteWithFile:#"Projectile.png"];
CGPoint MyVector = ccpSub(enem2.position,player.position );
MyVector = ccpNormalize(MyVector);
MyVector = ccpMult(MyVector, enem2.contentSize.width/2+10);
MyVector = ccpMult(MyVector,-1);
projectilebull.position = ccpAdd(enem2.position, MyVector);
[self addChild:projectilebull];
[proj addObject:projectilebull];
for(CCSprite *projectile in proj){
}
}
}
}
-(void)deleteprojectile:(CCSprite *)protime:(ccTime)dt{
NSMutableArray *timepro = [[NSMutableArray alloc]init];
[timepro addObject:protime];
for(CCSprite *objecttime in timepro){
[proj removeObject:objecttime];
[self removeChild:objecttime cleanup:YES];
}
}
It's a bit of a hack but this is what I use in my program, until I find a more elegant solution. I have a method in my game layer that I call to remove a node from its parent, like so:
-(void)removeNode:(CCNode*)node {
[node removeFromParentAndCleanup:YES];
}
And when I want to schedule a node for deletion after a delay, I call it like this:
[self performSelector:#selector(removeNode:) withObject:node afterDelay:delay];
Simple, and it works.
Change argument name in your selector to protime instead of projectile. The selector must match the signature defined in you object's class definition.
Your selector was not defined properly and probably the Timer is checking if the object implements the given selector.
I did not have time to test it so thanks to #RamyAlZuhouri for confirming.

Handling Double Tap in Cocos2d

This question is too primitive, but I have been trying for the last 8 hours, and it is eating away my energy ( and confidence levels too :))
In my class, I have registered for Targeted touches.
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:-1 swallowsTouches:YES];
I would like to check if the user is performing single tap or double tap. In ccTouchBegan method, first gets a touch with singleTap, then gets a touch with doubleTap. I found a very interesting solution for this one, in one of the Cocos2d Forums. ( I could not locate it now.. )
The solution goes like this.
switch (touch.tapCount) {
case 2:
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:#selector(handleSingleTouch:) object:singleTouchLocation];
// Handle Double Touch here
break;
case 1:
self.singleTapLocation = ccp(location.x,location.y);
self.singleTouchLocation = touch;
[self performSelector:#selector(handleSingleTouch:) withObject:touch afterDelay:0.3
];
break;
}
Everything looks to be working fine. Essentially, you schedule a single touch handler with a delay and see if it is actually a double tap. If it is a double tap, then cancel singletap handler and perform logic for double tap.
But my problem is, In the single touch handler (handleSingleTouch), I am adding a CCSprite to the UI. This action is not working. No sprite gets added. (Although the method is called.). In fact this works, If I call the selector with no delay, but with delay, the sprite is not added.
I am not a Objective C expert, So, I apologize if the question is too primitive.
Edit 1: The original thread.
Edit 2: Posting handleSingleTouch.. only relevant code.
-(void) handleSingleTouch:(UITouch * ) touch {
CGPoint location = [touch locationInView: [touch view]];
CGPoint glLocation = [MainSceneLayer locationFromTouch:touch];
//Single tap
CCLOG(#"Single tap: Adding marker image");
if(zoomedOut) {
CGPoint globalCoordinates = [quadConvertor convertLocalToGlobal:location
inActiveQuadrant:activeQuadrant];
if( [self isTouchValidForSelectedItem:globalCoordinates] == Matched) {
[self addMarkerImages:glLocation];
} else if([self isTouchValidForSelectedItem:globalCoordinates] == NotMatched) {
[missedLabel stopAllActions];
for (ImageQuadrants* quad in quadrants) {
if(quad.quadrantNumber == activeQuadrant) {
missedLabel.position = ccp((quad.center.x * -1)+glLocation.x , (quad.center.y * -1)+glLocation.y);
//markers.position = ccp((quad.center.x * -1)+touchPosition.x , 320);
}
}
id blinkAction = [CCBlink actionWithDuration:1 blinks:3];
id makeInvible = [CCCallFunc actionWithTarget:self selector:#selector(makeInvisible:)];
id seq = [CCSequence actions:blinkAction, makeInvible, nil];
[missedLabel runAction:seq];
} else {
[alreadyAccountedLabel stopAllActions];
for (ImageQuadrants* quad in quadrants) {
if(quad.quadrantNumber == activeQuadrant) {
alreadyAccountedLabel.position = ccp((quad.center.x * -1)+glLocation.x , (quad.center.y * -1)+glLocation.y);
//markers.position = ccp((quad.center.x * -1)+touchPosition.x , 320);
}
}
id blinkAction = [CCBlink actionWithDuration:1 blinks:3];
id makeInvible = [CCCallFunc actionWithTarget:self selector:#selector(makeInvisible1:)];
id seq = [CCSequence actions:blinkAction, makeInvible, nil];
[alreadyAccountedLabel runAction:seq];
}
}
swipeStartPoint = [touch locationInView:touch.view];
}
i dont know if thats a typo in your question only but your delay method is all wrong. There is no withDelay: argument. it should look like this:
[self performSelector:#selector(handleSingleTouch:) withObject:touch afterDelay:0.1];
EDIT:
Since your problem is most probably with the touch getting lost. Try [touch retain] before calling the delayed method. Another way is changing the handleSingleTouch: method to take two floats x and y or a CCPoint as arguments instead of a UITouch. Then you create the floats before the delayed method and pass them in the delayed method. This way you will avoid a memory leak from retaining a touch as well since most probably you cant release it after calling the delayed method.
hope this helps