Having issues with touchesBegan method - ios

I have my sound on logo showing up on the screen and the sound off logo appears when i test it. what I want it to do is change from sound on to sound off when I tap on it. The buttons do acknowledge the tap but nothing happens. I don't have much experience in change node images when they're tapped so I don't really know if I used the most efficient code. Can someone look over my code and see what's wrong? Thanks in advance!
#implementation MyScene
{
SKSpriteNode *soundLogo;
SKSpriteNode *soundOff;
}
-(void) addSoundOff:(CGSize)size {
soundOff = [SKSpriteNode spriteNodeWithImageNamed:#"soundOff"];
//resize sprite
soundOff.size = CGSizeMake(soundOff.size.width/2.25, soundOff.size.height/2.25);
//position it
soundOff.position = CGPointMake(65, 25);
//name sound off
soundOff.name = #"soundOff";
soundOff.zPosition = 0;
soundOff.alpha = 0;
//[self addChild:soundOff];
}
-(void) addSoundOn:(CGSize)size {
soundLogo = [SKSpriteNode spriteNodeWithImageNamed:#"soundLogo"];
//resize sprite
soundLogo.size = CGSizeMake(soundLogo.size.width/2.25, soundLogo.size.height/2.25);
//position sprite
CGPoint myPoint = CGPointMake(65, 25);
soundLogo.position = myPoint;
//name sound logo
soundLogo.name = #"soundOn";
//add action
//soundLogo.alpha = 1;
soundLogo.zPosition = 100;
[self addChild:soundLogo];
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
if ([node.name isEqualToString:#"soundOn"]) {
soundOff.zPosition = 100;
soundOff.alpha = 1;
soundLogo.alpha = 0;
soundLogo.zPosition = 0;
// [node removeFromParent];
// [node addChild:soundOff];
NSLog(#"sound on is pressed");
}
if ([node.name isEqualToString:#"soundOff"]) {
soundLogo.zPosition = 100;
soundLogo.alpha = 1;
soundOff.alpha = 0;
soundOff.zPosition = 0;
// [node removeFromParent];
// [node addChild:soundLogo];
NSLog(#"sound off is pressed");
}
}

It seems nothing wrong in your addSoundOff and addSoundOn functions. What you can do as one of the solutions to change alpha and zPosition properties of SKSpriteNode . And also createsoundOff and soundLogo as instance variables under the implementation. So here is the all code:
#import "MyScene.h"
#implementation MyScene
{
SKSpriteNode *soundLogo;
SKSpriteNode *soundOff;
}
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
/* Setup your scene here */
self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];
[self addSoundOn:self.size];
[self addSoundOff:self.size];
}
return self;
}
-(void) addSoundOff:(CGSize)size {
soundOff = [SKSpriteNode spriteNodeWithImageNamed:#"soundOff"];
//resize sprite
soundOff.size = CGSizeMake(soundOff.size.width/2.25, soundOff.size.height/2.25);
//position it
soundOff.position = CGPointMake(65, 25);
//name sound off
soundOff.name = #"soundOff";
soundOff.alpha = 0;
soundOff.zPosition = 0;
[self addChild:soundOff];
}
-(void) addSoundOn:(CGSize)size {
SKTexture *soundOn = [SKTexture textureWithImageNamed:#"soundLogo"];
soundLogo = [SKSpriteNode spriteNodeWithTexture:soundOn];
//resize sprite
soundLogo.size = CGSizeMake(soundLogo.size.width/2.25, soundLogo.size.height/2.25);
//position sprite
CGPoint myPoint = CGPointMake(65, 25);
soundLogo.position = myPoint;
//name sound logo
soundLogo.name = #"soundOn";
//add action
soundLogo.zPosition = 100;
[self addChild:soundLogo];
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
//sound logo pressed to turn sound on/off
if ([node.name isEqualToString:#"soundOn"]) {
soundOff.alpha = 1;
soundOff.zPosition = 100;
soundLogo.alpha = 0;
soundLogo.zPosition = 0;
NSLog(#"sound on is pressed");
}
if ([node.name isEqualToString:#"soundOff"]) {
soundOff.alpha = 0;
soundOff.zPosition = 0;
soundLogo.alpha = 1;
soundLogo.zPosition = 100;
NSLog(#"sound off is pressed");
}
}
#end

Related

Why the texture in my SKSpriteNode gets removed when it's done animating?

I have a SKSpriteNode, I'm Trying to animate it in my touchesbegan and the animation works fine but when it's done animating, the default texture for my SKSpriteNode is gone. My R.atlas contains images named R1,R2..R7 ,What am I doing wrong? Thanks a lot.
#interface MyScene()
{
SKSpriteNode * rightTubeNode;
}
#property NSArray* rightTubeAnimationArray;
#end
#implementation MyScene
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
SKTextureAtlas *rightTubeAtlas = [SKTextureAtlas atlasNamed:#"R"];
rightTubeTexture = [rightTubeAtlas textureNamed:#"R1"];
NSMutableArray *rightAnimFrames = [NSMutableArray array];
for (int i = 1; i <= rightTubeAtlas.textureNames.count; ++i){
NSString *texture =[NSString stringWithFormat:#"R%d",i];
[rightAnimFrames addObject:[rightTubeAtlas textureNamed:texture]];
}
self.rightTubeAnimationArray = rightAnimFrames;
rightTubeNode = [self createRightTubeNode];
rightTubeNode.position = CGPointMake(self.frame.size.width/2+rightTubeNode.frame.size.width/2,50);
rightTubeNode.zPosition = 0.1;
[self addChild:rightTubeNode];
}
return self;
}
- (SKSpriteNode *)createRightTubeNode
{
SKSpriteNode *rightTube = [SKSpriteNode spriteNodeWithTexture:rightTubeTexture];
rightTube = [SKSpriteNode spriteNodeWithTexture:rightTubeTexture];
rightTube.name = #"rightTubeNode";
return rightTube;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
CGPoint nodesLocation = CGPointMake(location.x,self.frame.size.height/2);
if (nodesLocation.x>self.frame.size.width/2) {
SKNode *archerNode = [self childNodeWithName:#"rightTubeNode"];
if (archerNode != nil){
SKAction *animate = [SKAction animateWithTextures:self.rightTubeAnimationArray
timePerFrame: 0.02];
[archerNode runAction:animate];
}
}
}
}
Re-adding the R.atlas (with checking the Create groups options box) without any further changes did the trick, Thanks to #Whirlwind

Objective C - SpriteKit - Unable to detect contact between ball and paddle node

I am trying to detect the collision between the ball node and either one of the paddle nodes but the message to confirm the collision is not being fired.
Could somebody help me understand where I am going wrong?
//categories for detecting contacts between nodes
static const uint32_t ballCategory = 0x1 << 0;
static const uint32_t paddleCategory = 0x1 << 1;
#interface GameScene ()
#property BOOL contentCreated;
#property(nonatomic) UITouch *playerOnePaddleControlTouch;
#property(nonatomic, weak) UITouch *paddleTouch;
#property(nonatomic) SKSpriteNode *paddleOneNode;
#property(nonatomic) SKSpriteNode *paddleTwoNode;
#property(nonatomic) SKSpriteNode *ballNode;
#property(nonatomic) SKLabelNode *playerOneScoreNode;
#property(nonatomic) SKLabelNode *playerTwoScoreNode;
#property(nonatomic) NSInteger playerOneScore;
#property(nonatomic) NSInteger playerTwoScore;
#end
#implementation GameScene
- (void)didMoveToView:(SKView *)view
{
if (!self.contentCreated)
{
[self createSceneContents];
self.contentCreated = YES;
}
}
- (void) createSceneContents
{
self.backgroundColor = [SKColor blackColor];
self.scaleMode = SKSceneScaleModeAspectFit;
[self addChild: [self newGameNode]];
self.physicsWorld.gravity = CGVectorMake(0, 0);
self.physicsWorld.contactDelegate = self;
// Create border around screen
SKPhysicsBody* borderBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
self.physicsBody = borderBody;
self.physicsBody.friction = 0;
// Create Paddle One
SKSpriteNode *paddleOne = [self newPaddle];
paddleOne.position = CGPointMake(CGRectGetMidX(self.frame)/8, CGRectGetMidY(self.frame));
paddleOne.name = #"paddleOne";
paddleOne.physicsBody.categoryBitMask = paddleCategory;
paddleOne.physicsBody.contactTestBitMask = ballCategory;
[self addChild:paddleOne];
// Create Paddle Two
SKSpriteNode *paddleTwo = [self newPaddle];
paddleTwo.position = CGPointMake((CGRectGetMaxX(self.frame) - CGRectGetMidX(self.frame) / 8), CGRectGetMidY(self.frame));
paddleTwo.name = #"paddleTwo";
paddleTwo.physicsBody.categoryBitMask = paddleCategory;
paddleTwo.physicsBody.contactTestBitMask = ballCategory;
[self addChild:paddleTwo];
// Create ball
SKSpriteNode *ball = [self newBall];
ball.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:ball];
ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:ball.frame.size.width/2];
ball.physicsBody.friction = 1.0f; //normally 1.0f
ball.physicsBody.restitution = 1.0f; //normally 1.0f
ball.physicsBody.linearDamping = 0.0f; //normally 0.0f
ball.physicsBody.allowsRotation = NO;
ball.physicsBody.categoryBitMask = ballCategory;
ball.physicsBody.contactTestBitMask = paddleCategory;
[ball.physicsBody applyImpulse:CGVectorMake(1.0f, -1.0f)];
// Create score labels
self.playerOneScoreNode = [SKLabelNode labelNodeWithFontNamed:#"Helvetica"];
self.playerTwoScoreNode = [SKLabelNode labelNodeWithFontNamed:#"Helvetica"];
self.playerOneScoreNode.fontColor = self.playerOneScoreNode.fontColor = [SKColor whiteColor];
self.playerOneScoreNode.fontSize = self.playerTwoScoreNode.fontSize = 90;
self.playerOneScoreNode.position = CGPointMake((CGRectGetWidth(self.frame))* 0.25, (CGRectGetHeight(self.frame)) - 80);
self.playerTwoScoreNode.position = CGPointMake((CGRectGetWidth(self.frame)) * 0.75, (CGRectGetHeight(self.frame)) - 80);
[self addChild:self.playerOneScoreNode];
[self addChild:self.playerTwoScoreNode];
// Set Scores to 0
self.playerOneScore = 7;
self.playerTwoScore = 0;
self.playerOneScoreNode.text = [NSString stringWithFormat:#"%ld",self.playerOneScore];
self.playerTwoScoreNode.text = [NSString stringWithFormat:#"%ld",self.playerTwoScore];
}
- (SKSpriteNode *)newPaddle
{
SKSpriteNode *paddle = [[SKSpriteNode alloc]initWithColor:[SKColor whiteColor] size:CGSizeMake(16,64)];
return paddle;
}
- (SKSpriteNode *)newBall
{
SKSpriteNode *ball = [[SKSpriteNode alloc]initWithColor:[SKColor redColor] size:CGSizeMake(16, 16)];
return ball;
}
- (SKLabelNode *) newGameNode
{
SKLabelNode *gameNode = [SKLabelNode labelNodeWithFontNamed:#"Chalkduster"];
gameNode.text = #" Pong";
gameNode.fontSize = 50;
gameNode.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
gameNode.fontColor = [SKColor blueColor];
return gameNode;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
self.paddleTouch = [touches anyObject];
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInNode:self];
SKNode *paddleOne = [self childNodeWithName:#"paddleOne"];
SKNode *paddleTwo = [self childNodeWithName:#"paddleTwo"];
if (touchPoint.x < CGRectGetMidX(self.frame)) {
paddleOne.position = CGPointMake(paddleOne.position.x, touchPoint.y);
}
else
{
paddleTwo.position = CGPointMake(paddleTwo.position.x, touchPoint.y);
}
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
if (self.paddleTouch) {
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInNode:self];
CGPoint previousPoint = [touch previousLocationInNode:self];
SKSpriteNode *paddleOne = (SKSpriteNode*)[self childNodeWithName:#"paddleOne"];
SKSpriteNode *paddleTwo = (SKSpriteNode*)[self childNodeWithName:#"paddleTwo"];
int paddleOneY = paddleOne.position.y + (touchPoint.y - previousPoint.y);
int paddleTwoY = paddleTwo.position.y + (touchPoint.y - previousPoint.y);
if (touchPoint.x < CGRectGetMidX(self.frame)) {
paddleOne.position = CGPointMake(paddleOne.position.x, paddleOneY);
}
else
{
paddleTwo.position = CGPointMake(paddleTwo.position.x, paddleTwoY);
}
}
}
// React to collision's between nodes/bodies
// Currently not working....need to understand this set of code.
-(void)didBeginContact:(SKPhysicsContact *)contact
{
SKPhysicsBody *firstBody;
SKPhysicsBody *secondBody;
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
{
firstBody = contact.bodyA;
secondBody = contact.bodyB;
}
else
{
firstBody = contact.bodyB;
secondBody = contact.bodyA;
}
if (firstBody.categoryBitMask == ballCategory && secondBody.categoryBitMask == paddleCategory)
{
NSLog(#"Ball has touched Paddle");
}
}
#end
Your paddleOne and paddleTwo does not have SKPhysicsBody.
Add these (change size of physics body if needed)
paddleOne.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize: paddleOne.size];
paddleTwo.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize: paddleTwo.size];

Removing specific nodes in SpriteKit

Need some help as a beginner: I've got different nodes: 4 squares (sprite1) and 1 counter (counterLabel, counts the nodes, which have been removed). I want to remove the 4 squares by touching them. With the code below the squares can be removed, but also the counter. Strangely enough, because I tried to address the square nodes (sprite1) exclusively. Is there any possibility to remove the square nodes (sprite 1) exclusively?
#implementation GameScene {
BOOL updateLabel;
SKLabelNode *counterLabel;
}
int x;
int y;
int counter;
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]){
self.backgroundColor = [SKColor /*colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0*/ whiteColor];
counter = 0;
updateLabel = false;
counterLabel = [SKLabelNode labelNodeWithFontNamed:#"Chalkduster"];
counterLabel.name = #"myCounterLabel";
counterLabel.text = #"0";
counterLabel.fontSize = 48;
counterLabel.fontColor = [SKColor greenColor];
//counterLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeCenter;
//counterLabel.verticalAlignmentMode = SKLabelVerticalAlignmentModeBottom;
counterLabel.position = CGPointMake(50,50); // change x,y to location you want
//counterLabel.zPosition = 900;
[self addChild: counterLabel];
}
return self;
}
-(void) didMoveToView:(SKView *)view {
SKTexture *texture1 = [SKTexture textureWithImageNamed:#"square"];
for (int i = 0; i < 4; i++) {
x = arc4random()%668;
y = arc4random()%924;
SKSpriteNode *sprite1 = [SKSpriteNode spriteNodeWithTexture:texture1];
sprite1.position = CGPointMake(x, y);
sprite1.name = #"square";
[self addChild:sprite1];
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
NSArray *nodes = [self nodesAtPoint: [touch locationInNode: self]];
for (SKNode *sprite1 in nodes) {
[sprite1 removeFromParent];
counter ++;
updateLabel = true;
}
}
-(void)update:(CFTimeInterval)currentTime {
if(updateLabel == true){
counterLabel.text = [NSString stringWithFormat:#"%i",counter];
updateLabel = false;
}
}
#end
you should use the property name of SKSpriteNode
in this case you can do:
for (SKNode *sprite1 in nodes) {
if(![sprite1.name isEqualToString:#"myCounterLabel"]) {
[sprite1 removeFromParent];
}
counter ++;
updateLabel = true;
}
So if the SKNode name is different to the name of counterLabel, then removeFromParent.

Issues with touchesBegan method

So the problem is that when I start it the soundOff button is above the soundOn but it's invisible. So all I see is the soundOn button, when I try to tap the soundOn button it really is just hitting the soundOff button and not giving it a chance to run the touchesBegan method properly.
#implementation GameScene
{
SKSpriteNode *soundLogo;
SKSpriteNode *soundOff;
}
-(void) addSoundOff:(CGSize)size {
soundOff = [SKSpriteNode spriteNodeWithImageNamed:#"soundOff"];
//resize sprite
soundOff.size = CGSizeMake(soundOff.size.width/2.25, soundOff.size.height/2.25);
//position it
soundOff.position = CGPointMake(65, 25);
//name sound off
soundOff.name = #"soundOff";
soundOff.alpha = 0;
[self addChild:soundOff];
}
-(void) addSoundOn:(CGSize)size {
SKTexture *soundOn = [SKTexture textureWithImageNamed:#"soundLogo"];
soundLogo = [SKSpriteNode spriteNodeWithTexture:soundOn];
//resize sprite
soundLogo.size = CGSizeMake(soundLogo.size.width/2.25, soundLogo.size.height/2.25);
//position sprite
CGPoint myPoint = CGPointMake(65, 25);
soundLogo.position = myPoint;
//name sound logo
soundLogo.name = #"soundOn";
//add action
[self addChild:soundLogo];
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
//sound logo pressed to turn sound on/off
if ([node.name isEqualToString:#"soundOn"]) {
soundOff.alpha = 1;
soundLogo.alpha = 0;
NSLog(#"sound on is pressed");
}
if ([node.name isEqualToString:#"soundOff"]) {
soundOff.alpha = 0;
soundLogo.alpha = 1;
NSLog(#"sound off is pressed");
}
}
Rather then changing the alpha to 0/1 what you can do is remove sprite from parent and you can add to child.
Don't add sound off and sound on button at same time first add the default button that is sound on.
now when the sound on button is clicked then remove the sound on button from parent and add sound off.
-(void) addSoundOff:(CGSize)size {
soundOff = [SKSpriteNode spriteNodeWithImageNamed:#"soundOff"];
//resize sprite
soundOff.size = CGSizeMake(soundOff.size.width/2.25, soundOff.size.height/2.25);
//position it
soundOff.position = CGPointMake(65, 25);
//name sound off
soundOff.name = #"soundOff";
soundOff.alpha = 0;
//-------------Remove below line-----------------//
//[self addChild:soundOff];
//Dont add sound off button.....
}
-(void) addSoundOn:(CGSize)size {
SKTexture *soundOn = [SKTexture textureWithImageNamed:#"soundLogo"];
soundLogo = [SKSpriteNode spriteNodeWithTexture:soundOn];
//resize sprite
soundLogo.size = CGSizeMake(soundLogo.size.width/2.25, soundLogo.size.height/2.25);
//position sprite
CGPoint myPoint = CGPointMake(65, 25);
soundLogo.position = myPoint;
//name sound logo
soundLogo.name = #"soundOn";
//add action
[self addChild:soundLogo];
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
//sound logo pressed to turn sound on/off
if ([node.name isEqualToString:#"soundOn"]) {
[soundLogo removeFromParent];
[self addChild:soundOff];
NSLog(#"sound on is pressed");
}
if ([node.name isEqualToString:#"soundOff"]) {
[soundOff removeFromParent];
[self addChild:soundLogo];
}
}

Cocos2d EXC_BAD_ACCESS

I am new to cocos2d and suddenly got this EXC_BAD_ACCESS,
I made a new winning menu and i got the error
I think the error is because i called a released object, but i dont release anything?
My Debug Console had no error, which is strange
here is my Level_1.m
//
// Level_1.m
// iPadGame
//
// Created by My Name on 1/25/12.
// Copyright 2012 __MyCompanyName__. All rights reserved.
//
#import "Level_1.h"
#import "HelloWorldLayer.h"
CCSprite *player;
CCSprite *enemy;
CCSprite *enemy2;
CCSprite *enemy3;
CCSprite *star;
CCSprite *star2;
CCSprite *star3;
CCSprite *bg;
CCSprite *toolBar;
CCLabelTTF *youWin;
bool movePlayer;
#implementation Level_1
#synthesize score;
+(CCScene *) scene {
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
Level_1 *layer = [Level_1 node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
-(void) setUpWinMenu {
[CCMenuItemFont setFontName:#"Marker Felt"];
[CCMenuItemFont setFontSize:75];
CCMenuItem *MainMenu = [CCMenuItemFont itemFromString:#"Main Menu" target:self selector:#selector(gotoMainMenu)];
CCMenu *WinMenu = [CCMenu menuWithItems:MainMenu, nil];
[self addChild:WinMenu];
MainMenu.position = ccp(400,500);
}
// on "init" you need to initialize your instance
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init]))
{
self.isTouchEnabled = YES;
scoreNumber = 10;
bg = [CCSprite spriteWithFile:#"metal_background.jpeg"];
bg.position = ccp(512,384);
[self addChild:bg];
toolBar = [CCSprite spriteWithFile:#"ToolBar.png"];
toolBar.position = ccp(512,-30);
[self addChild:toolBar];
score = [CCLabelAtlas labelWithString:#"0123456789" charMapFile:#"ScoreFinal.png" itemWidth:50 itemHeight:75 startCharMap:'.'];
[self addChild:score];
score.position = ccp (-100,15);
CCLabelTTF *scoreLabel = [CCLabelTTF labelWithString:#"Score:" fontName:#"Marker Felt" fontSize:45];
scoreLabel.position = ccp(score.position.x + 275,score.position.y + 40);
scoreLabel.color = ccc3(0, 0, 0);
[self addChild:scoreLabel];
star = [CCSprite spriteWithFile:#"Star.png"];
star.position = ccp(400,600);
[self addChild:star];
star2 = [CCSprite spriteWithFile:#"Star.png"];
star2.position = ccp(600,600);
star3 = [CCSprite spriteWithFile:#"Star.png"];
star3.position = ccp(200,600);
player = [CCSprite spriteWithFile:#"ball.png"];
player.position = ccp(500,300);
[self addChild:player];
enemy = [CCSprite spriteWithFile:#"SpaceShip.png"];
enemy.position = ccp(150,600);
[self addChild:enemy];
enemy2 = [CCSprite spriteWithFile:#"SpaceShip.png"];
enemy2.position = ccp(250,600);
[self addChild:enemy2];
enemy3 = [CCSprite spriteWithFile:#"SpaceShip.png"];
enemy3.position = ccp(350,600);
[self addChild:enemy3];
[self schedule:#selector(enemyMove) interval:0.01];
[self schedule:#selector(collisionDetection) interval:0.01];
[self schedule:#selector(getStar) interval:0.01];
NSString *string = [NSString stringWithFormat:#"Score: %i", (int)scoreNumber];
[score setString:string];
x = 15;
x2 = 15;
x3 = 15;
y = 15;
Bx = 10;
By = 10;
movePlayer = FALSE;
CCRepeatForever *repeat = [CCRepeatForever actionWithAction: [CCRotateBy actionWithDuration:2 angle:360]];
[star runAction:repeat];
star.visible = 1;
}
return self;
}
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch* myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView: [myTouch view]];
location = [[CCDirector sharedDirector]convertToGL:location];
CGRect playerRect = CGRectMake(player.position.x - (player.contentSize.width/2),
player.position.y - (player.contentSize.height/2),
player.contentSize.width,
player.contentSize.height);
CGRect Tlocation = CGRectMake(location.x, location.y, 10, 10);
NSLog(#"Touch Began");
if (CGRectIntersectsRect (Tlocation, playerRect)) {
player.position = location;
movePlayer = TRUE;
}
}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *myTouch = [touches anyObject];
CGPoint point = [myTouch locationInView:[myTouch view]];
point = [[CCDirector sharedDirector] convertToGL:point];
if (movePlayer == TRUE) {
player.position = point;
if (player.position.y < 110) {
player.position = ccp(player.position.x, 111);
}
}
}
-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(#"Touch ended");
movePlayer = FALSE;
}
-(void) enemyMove {
enemy.position = ccp(enemy.position.x + x, enemy.position.y);
enemy2.position = ccp(enemy2.position.x - x2, enemy2.position.y);
enemy3.position = ccp(enemy3.position.x + x3, enemy3.position.y);
if (enemy.position.x > 1024 || enemy.position.x < 0) {
x = -x;
}
if (enemy2.position.x > 1024 || enemy2.position.x < 0) {
x2 = -x2;
}
if (enemy3.position.x > 1024 || enemy3.position.x < 0) {
x3 = -x3;
}
if (enemy.position.y > 768 || enemy.position.y < 120) {
y = -y;
}
}
-(void) collisionDetection {
if (CGRectIntersectsRect(player.boundingBox, enemy.boundingBox)) {
[self schedule:#selector(collisionAlert)];
}
if (CGRectIntersectsRect(player.boundingBox, enemy2.boundingBox)) {
[self schedule:#selector(collisionAlert)];
}
if (CGRectIntersectsRect(player.boundingBox, enemy3.boundingBox)) {
[self schedule:#selector(collisionAlert)];
}
}
-(void) getStar {
if (CGRectIntersectsRect(player.boundingBox, star.boundingBox)) {
NSLog(#"Got Star!");
scoreNumber += 100;
NSString *string = [NSString stringWithFormat:#"Score: %i", (int)scoreNumber];
[score setString:string];
[self addChild:star2];
if (star.visible == 1) {
}
}
if (CGRectIntersectsRect(player.boundingBox, star2.boundingBox)) {
NSLog(#"Got Star!");
scoreNumber += 100;
NSString *string = [NSString stringWithFormat:#"Score: %i", (int)scoreNumber];
[score setString:string];
[self addChild:star3];
}
if (CGRectIntersectsRect(player.boundingBox, star3.boundingBox)) {
youWin = [CCLabelTTF labelWithString:#"You Win" fontName:#"Marker Felt" fontSize:75];
youWin.position = ccp(500,400);
[self addChild:youWin];
[self setUpWinMenu];
NSLog(#"Got Star!");
scoreNumber += 100;
NSString *string = [NSString stringWithFormat:#"Score: %i", (int)scoreNumber];
[score setString:string];
player.position = ccp(player.position.x - 10, player.position.y - 20);
[self unschedule:#selector(enemyMove)];
[self unschedule:#selector(collisionAlert)];
[self unschedule:#selector(getStar)];
}
return;
}
-(void) collisionAlert {
player.position = ccp(player.position.x - 10, player.position.y - 20);
[self unschedule:#selector(enemyMove)];
UIAlertView* dialog = [[UIAlertView alloc] init];
[dialog setDelegate:self];
[dialog setTitle:#"Fail"];
[dialog setMessage:#"You are a Failure!"];
[dialog addButtonWithTitle:#"Goto Main Menu"];
[dialog addButtonWithTitle:#"Retry!"];
[dialog addButtonWithTitle:#"Dont push this button"];
[dialog show];
[dialog release];
[self unschedule:#selector(collisionAlert)];
}
-(void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == 0) {
[[CCDirector sharedDirector] replaceScene:[CCTransitionFlipAngular transitionWithDuration:1 scene:[HelloWorldLayer node]]];
}
if (buttonIndex == 1) {
[[CCDirector sharedDirector] replaceScene:[Level_1 node]];
}
if (buttonIndex == 2) {
[self schedule:#selector(noting)];
}
}
-(void) gotoMainMenu {
[[CCDirector sharedDirector] replaceScene:[CCTransitionJumpZoom transitionWithDuration:1 scene:[HelloWorldLayer node]]];
}
#end
im not finished completely but there maybe a few empty methods but im sure thats not whats causing the problem
All this objects:
CCSprite *player;
CCSprite *enemy;
CCSprite *enemy2;
CCSprite *enemy3;
CCSprite *star;
CCSprite *star2;
CCSprite *star3;
CCSprite *bg;
CCSprite *toolBar;
are being allocated with autorelease methods, such as CCSprite spriteWithFile: and then, when you access these objects in other methods, like you do at ccTouchesBegan: withEvent: they are already deallocated, and you get the EXC_BAD_ACCESS
One thing you can do to fix it, is to call the spriteWithFile: method followed by a retain call, like
toolBar = [[CCSprite spriteWithFile:#"ToolBar.png"] retain];
But don't forget to release the retained objects on your Level_1's class dealloc (which I didn't see implemented in your class)
-(void) dealloc {
[toolBar release];
[super dealloc]
}
Even if you don't see anything on the console, if you run the app under the debugger, you should be able to inspect the call stack at the moment of the crash.
This will tell you clearly if you are accessing some already deallocated object, or possibly trying to send a message.

Resources