Why does CGPathRelease cause memory leak? - ios

When I try to release a path it will cause a memory leak that is about 5 megabytes big. Every time i call CGreleasePath the ram memory usage will increase again by 5 megabytes. What could be the reason that is causing this memory leak?
This is the code where all my paths are getting used:
//viewcontroller.h
CGMutablePathRef path;
//viewcontroller.m
-(void)viewDidLoad{
path = CGPathCreateMutable;
timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:#selector(movement1) userInfo:nil repeats:YES];
timer2 = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:#selector(motor) userInfo:nil repeats:YES];
}
-(void)movement1{
CGPathMoveToPoint(path, NULL, greentmporary.x, greentmporary.y);
CGPathAddLineToPoint(path, NULL, greenpoint1.x, greenpoint1.y);
}
-(void)motor{
CGPathRef thickpath = NULL;
thickpath = CGPathCreateCopyByStrokingPath(path, NULL, (6+bigsizeYellow), kCGLineCapSquare, kCGLineJoinMiter, 0);
if (CGPathContainsPoint(thickpath, NULL, greenpoint1, NO) && krockamedgreen == NO) {
NSLog(#"YES");
[self reset]
}
if (CGPathContainsPoint(thickpath, NULL, point1, NO) && krockamedgreen == NO) {
NSLog(#"YES");
[self reset]
}
if (thickpath) {
CFRelease(thickpath);
thickpath = NULL;
}
}
-(void)reset{
path = NULL;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//start again
{
path = CGPathCreateMutable;
}

Related

<Error>: CGAffineTransformInvert: singular matrix error

I am getting the error : CGAffineTransformInvert: singular matrix error every time i run my app but i do not know what is causing the problem. The code is below could someone help me please. Anyone who answers i thank in advance.
#import "Squirrel.h"
#interface Squirrel ()
#end
#implementation Squirrel
-(void)Scoring{
ScoreNumber = ScoreNumber + AddedScore;
AddedScore = AddedScore - 1;
if (AddedScore < 0){
AddedScore = 0;
}
Score.text=[NSString stringWithFormat:#"Score: %i", ScoreNumber];
}
-(void)Gameover{
Acorn1.hidden=YES;
Branch1.hidden=YES;
}
-(void)Losing{
if(CGRectContainsRect(Sammy.frame, Acorn1.frame)){
AddedScore=1;
RandomPosition=arc4random()%248;
RandomPosition=RandomPosition+36;
Acorn1.center=CGPointMake(RandomPosition, 88);
}
if(CGRectContainsRect(Sammy.frame, Acorn2.frame)){
AddedScore=1;
/*RandomPosition=arc4random()%248;
RandomPosition=RandomPosition+36;
Acorn2.center=CGPointMake(RandomPosition, 56);*/
}
if(CGRectContainsRect(Sammy.frame, Acorn3.frame)){
AddedScore=1;
}
if(CGRectContainsRect(Sammy.frame, Branch1.frame)){
//[self Gameover];
AddedScore=1;
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
SquirrelLeft=NO;
SquirrelRight=NO;
StopSideMovement=YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self.view];
if(point.x < 160){
SquirrelLeft=YES;
}
else{
SquirrelRight=YES;
}
}
-(void)moving{
Sammy.center = CGPointMake(Sammy.center.x + SideMovement, 366);
if(Acorn1.center.y > 463){
RandomPosition = arc4random() %248;
RandomPosition = RandomPosition + 36;
Acorn1.center = CGPointMake(RandomPosition, 16);
}
if(Acorn2.center.y > 463){
RandomPosition = arc4random() %248;
RandomPosition = RandomPosition + 36;
Acorn2.center = CGPointMake(RandomPosition, 16);
}
if(Acorn3.center.y > 463){
RandomPosition = arc4random() %248;
RandomPosition = RandomPosition + 36;
Acorn3.center = CGPointMake(RandomPosition, 16);
}
if(Branch1.center.y > 463){
RandomPosition = arc4random() %248;
RandomPosition = RandomPosition + 36;
Branch1.center = CGPointMake(RandomPosition, 16);
}
if(Branch2.center.y > 463){
RandomPosition = arc4random() %248;
RandomPosition = RandomPosition + 36;
Branch2.center = CGPointMake(RandomPosition, 16);
}
if(Branch3.center.y > 463){
RandomPosition = arc4random() %248;
RandomPosition = RandomPosition + 36;
Branch3.center = CGPointMake(RandomPosition, 16);
}
if(Branch4.center.y > 463){
RandomPosition = arc4random() %248;
RandomPosition = RandomPosition + 36;
Branch4.center = CGPointMake(RandomPosition, 16);
}
if(SquirrelLeft == YES){
SideMovement = SideMovement-0.8;
if(SideMovement < -5){
SideMovement = -5;
}
}
if(SquirrelRight ==YES){
SideMovement = SideMovement + 0.8;
if(SideMovement > 5){
SideMovement = 5;
}
}
if(StopSideMovement == YES && SideMovement>0){
SideMovement = SideMovement - 0.1;
if (SideMovement < 0){
SideMovement = 0;
StopSideMovement=NO;
}
}
if (StopSideMovement == YES && SideMovement<0){
SideMovement=SideMovement+0.1;
if(SideMovement>0){
SideMovement=0;
StopSideMovement=NO;
}
}
if(AddedScore == 1 && CGRectContainsRect(Sammy.frame, Acorn1.frame)){
Branch1.center = CGPointMake(Branch1.center.x, Branch1.center.y + 6);
Branch2.center = CGPointMake(Branch2.center.x, Branch2.center.y + 6);
Branch3.center = CGPointMake(Branch3.center.x, Branch3.center.y + 6);
Branch4.center = CGPointMake(Branch4.center.x, Branch4.center.y + 6);
Acorn2.center = CGPointMake(Acorn2.center.x, Acorn2.center.y + 5);
Acorn3.center = CGPointMake(Acorn3.center.x, Acorn3.center.y + 5);
}
}
-(void)moveBranch1{
Branch1.center = CGPointMake(Branch1.center.x, Branch1.center.y + 6);
}
-(void)moveBranch2{
Branch2.center = CGPointMake(Branch2.center.x, Branch2.center.y + 6);
}
-(void)moveBranch3{
Branch3.center = CGPointMake(Branch3.center.x, Branch3.center.y + 6);
}
-(void)moveBranch4{
Branch4.center = CGPointMake(Branch4.center.x, Branch4.center.y + 6);
}
-(void)moveAcorn1{
Acorn1.center = CGPointMake(Acorn1.center.x, Acorn1.center.y + 5);
}
-(void)moveAcorn2{
Acorn2.center = CGPointMake(Acorn2.center.x, Acorn2.center.y + 5);
}
-(void)moveAcorn3{
Acorn3.center = CGPointMake(Acorn3.center.x, Acorn3.center.y + 5);
}
- (IBAction)Start:(id)sender {
Acorn1.hidden=NO;
Acorn2.hidden=NO;
Acorn3.hidden=NO;
Branch1.hidden=NO;
Branch2.hidden=NO;
Branch3.hidden=NO;
Branch4.hidden=NO;
Title.hidden=YES;
Mu.hidden=YES;
Main.hidden=YES;
Start.hidden=YES;
HighScore.hidden=YES;
How.hidden=YES;
MoveAcorn1 = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(moveAcorn1) userInfo:nil repeats:YES];
MoveAcorn2 = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(moveAcorn2) userInfo:nil repeats:YES];
MoveAcorn3 = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(moveAcorn3) userInfo:nil repeats:YES];
MoveBranch1 = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(moveBranch1) userInfo:nil repeats:YES];
MoveBranch2 = [NSTimer scheduledTimerWithTimeInterval:0.09 target:self selector:#selector(moveBranch2) userInfo:nil repeats:YES];
MoveBranch3 = [NSTimer scheduledTimerWithTimeInterval:0.09 target:self selector:#selector(moveBranch3) userInfo:nil repeats:YES];
MoveBranch4 = [NSTimer scheduledTimerWithTimeInterval:0.09 target:self selector:#selector(moveBranch4) userInfo:nil repeats:YES];
Moving = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(moving) userInfo:nil repeats:YES];
losing = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(Losing) userInfo:nil repeats:YES];
Scoring = [NSTimer scheduledTimerWithTimeInterval:0.00000001 target:self selector:#selector(Scoring) userInfo:nil repeats:YES];
RandomPosition=arc4random()%248;
RandomPosition=RandomPosition+36;
Acorn1.center=CGPointMake(RandomPosition, 88);
RandomPosition=arc4random()%248;
RandomPosition=RandomPosition+36;
Acorn2.center=CGPointMake(RandomPosition, 56);
RandomPosition=arc4random()%248;
RandomPosition=RandomPosition+36;
Acorn3.center=CGPointMake(RandomPosition, 22);
RandomPosition=arc4random()%248;
RandomPosition=RandomPosition+36;
Branch1.center=CGPointMake(RandomPosition, 35);
RandomPosition=arc4random()%248;
RandomPosition=RandomPosition+36;
Branch2.center=CGPointMake(RandomPosition, 25);
RandomPosition=arc4random()%248;
RandomPosition=RandomPosition+36;
Branch3.center=CGPointMake(RandomPosition, 77);
RandomPosition=arc4random()%248;
RandomPosition=RandomPosition+36;
Branch4.center=CGPointMake(RandomPosition, 43);
}
- (void)viewDidLoad {
Acorn1.hidden=YES;
Acorn2.hidden=YES;
Acorn3.hidden=YES;
Branch1.hidden=YES;
Branch2.hidden=YES;
Branch3.hidden=YES;
Branch4.hidden=YES;
[super viewDidLoad];

IOS - App freezes in game using Cocos2d [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have just started developing a game, new to Objective-c. Basically at the moment you can move the spaceship around and the spaceship fires continually and there are asteroids coming from the top of screen. But my app freezes after a minute every time why is this?
CODE
#import "AppDelegate.h"
#pragma mark - HelloWorldLayer
// HelloWorldLayer implementation
#implementation HelloWorldLayer
// Helper class method that creates a Scene with the HelloWorldLayer as the only child.
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
HelloWorldLayer *layer = [HelloWorldLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
// on "init" you need to initialize your instance
-(id) init
{
if( (self=[super init]) ) {
self.isTouchEnabled = YES;
moveLeft = NO;
moveRight = NO;
speed = 3;
fireSpeed = 8;
fireArray = [[NSMutableArray alloc] init];
CGSize winSize = [[CCDirector sharedDirector] winSize];
CCSprite *bg = [[CCSprite alloc] initWithFile:#"space_bg.jpg"];
[bg setPosition:ccp(160, 240)];
CGSize imageSize = bg.contentSize;
bg.scaleX = winSize.width / imageSize.width;
bg.scaleY = winSize.height / imageSize.height;
bg.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:bg];
ship = [[CCSprite alloc] initWithFile:#"ship.png"];
[ship setPosition:ccp(100, 100)];
[self addChild:ship];
[self schedule:#selector(fireLoop:)];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(fireCreate)
userInfo:nil
repeats:YES];
int t = arc4random() % 5;
timer3 = [NSTimer scheduledTimerWithTimeInterval:t
target:self
selector:#selector(asteroidTimer)
userInfo:nil
repeats:YES];
}
return self;
}
NSTimer *timer3;
NSTimer *timer2;
NSTimer *tmpTimer;
-(void)asteroidTimer {
int t = arc4random() % 10;
timer2 = [NSTimer scheduledTimerWithTimeInterval:0
target:self
selector:#selector(asteroidCreate)
userInfo:nil
repeats:YES];
}
-(void)asteroidCreate {
[timer2 invalidate];
[tmpTimer invalidate];
CGSize winSize = [[CCDirector sharedDirector] winSize];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"asteroids.plist"];
CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:#"asteroids.png"];
NSMutableArray *asteroidAnimFrames = [NSMutableArray array];
for(int i=1; i <= 8; i++) {
[asteroidAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:#"asteroid%d.png", i]]];
}
CCAnimation *moveAsteroidAnim = [CCAnimation animationWithFrames:asteroidAnimFrames delay:0.1f];
CCSprite *asteroid = [CCSprite spriteWithSpriteFrameName:#"asteroid1.png"];
int x = arc4random() % 320;
int y = arc4random() % 480;
asteroid.position = ccp(x, 480);
CCAction *asteroidAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:moveAsteroidAnim restoreOriginalFrame:NO]];
int q = arc4random() % 320;
int r = arc4random() % 10;
CCAction *moveAction = [CCMoveTo actionWithDuration:r position:ccp(q, -50)];
[asteroid runAction:moveAction];
[asteroid runAction:asteroidAction];
[spriteSheet addChild:asteroid];
[self addChild:spriteSheet];
int t = arc4random() % 10;
tmpTimer = [NSTimer scheduledTimerWithTimeInterval:t
target:self
selector:#selector(asteroidTimer)
userInfo:nil
repeats:YES];
}
-(void)fireLoop:(ccTime)fl {
if(fireArray.count > 0) {
for(int i = 0; i < fireArray.count; i++){
CCSprite *tmpFire = [fireArray objectAtIndex:i];
if(tmpFire.position.y < 500){
[tmpFire setPosition:ccp([tmpFire position].x, [tmpFire position].y + fireSpeed)];
}else{
[fireArray removeObjectAtIndex:i];
}
}
} else
{
}
}
-(void)fireCreate {
int shootPositionX = [ship position].x;
int shootPositionY = ([ship position].y) + 35;
CCSprite *fire;
fire = [[CCSprite alloc] initWithFile:#"fire.png"];
[fire setPosition:ccp(shootPositionX, shootPositionY)];
[fireArray addObject:fire];
[self addChild:fire];
[fire release];
}
-(void)gameLoop:(ccTime)dt {
int shipPositionX = 41/2;
if([ship position].x > shipPositionX){
[ship setPosition:ccp([ship position].x - speed, [ship position].y)];
}
}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
for(UITouch *t in touches){
CGPoint point = [self convertTouchToNodeSpace:t];
//if(point.x <= 160){
// moveRight = NO;
// moveLeft = YES;
//}else{
// moveRight =YES;
// moveLeft = NO;
//}
if(allowedToMove)
[ship setPosition:ccp(point.x, point.y + 76)];
}
}
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
for(UITouch *t in touches){
CGPoint point = [self convertTouchToNodeSpace:t];
int shipX = [ship position].x;
int shipY = [ship position].y;
if (CGRectContainsPoint(CGRectMake (shipX - 20.5, shipY - 96, 50, 50), point))
{
allowedToMove = true;
}
}
}
-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
for(UITouch *t in touches){
CGPoint point = [self convertTouchToNodeSpace:t];
pointXLeft = point.x;
pointYLeft = point.y;
allowedToMove = false;
}
}
// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
// in case you have something to dealloc, do it in this method
// in this particular example nothing needs to be released.
// cocos2d will automatically release all the children (Label)
// don't forget to call "super dealloc"
[super dealloc];
}
In general track down what seems to be causing it. What does the debugger say? Did you stop the execution or set a breakpoint somewhere that might be problematic? What about exception breakpoints? If those don't work take out your timers and see if you have any change. What about your fire methods?
Also your use of timers look weird and should be the first area you look. Side note, for the asteroids why are you not running the two actions you want to run on the new asteroid using CCSpawn?
In addition are you ever removing projectiles that you shoot from the screen or the asteroids that are no longer needed? If not you should.
But to answer your question the problem looks most likely a timer issue. Your use of timers are wrong. You have timer-3 call asteroid timer, which in turns creates timer-2 that calls asteroid create, which in turns invalidates timer-2 (that had an interval of 0 which makes it look a little unnecessary) and also creates a tmp-timer that calls asteroid create. Timer 3 is left to continuously do what it wants, which is all the steps above, at every x number of seconds. Even though tmp-timer seems to be trying to spawn more asteroid creations and take over the process, instead that looks both incorrect and odd. And you are doing this with a few global timers that can, seemingly have a valid timer but is overridden by a new allocation, just to be invalidated by another method randomly soon after even though what it was trying to invalidate technically was leaked and no longer has a pointer to it, thus invalidating the wrong instance to the wrong timer. Keep in mind your tmp-timer and timer-3 has random intervals. If tmp-timer has an interval of 3 seconds and timer-3 has a 9 second interval at some point something looks like it is bound to go wrong. It is hard to say by glancing at it just how, but it looks inevitable.
Or at least I think that is what is happening. Again the code makes very weird and potentially error prone use of timers.
Also timer-1 is going to keep creating sprites unchecked without those sprites ever going away. Something to think about for sure.
Edit (Solution):
If I understand what you are trying to do you want to create timers every variable amount of seconds that, at the end, creates a new asteroid. There are two things that stand out with this. You want something to call the creation of an asteroid, and something else to do the actual create:
- (void)countDownToCreateNextAsteroid
{
int minTime = 1;
int maxTime = 10;
int randomTime = (arc4random() % (maxTime - minTime)) + minTime;
id countdownDelay = [CCDelayTime actionWithDuration:randomTime];
id creationMethod = [CCCallFunc actionWithTarget:self selector:#selector(createAsteroid)];
id countdownToCreateSeq = [CCSequence actions:countdownDelay, creationMethod, nil];
[self stopAllActions];
[self runAction:countdownToCreateSeq];
}
- (void)createAsteroid
{
CGPoint someStartPosition = ccp(1024.0f, 512.0f);
CCSprite* asteroid = [CCSprite spriteWithFile:#"someImage.png"];
asteroid.position = someStartPosition;
// asterdoid dot yada yada = ....
[self addChild:asteroid];
float someDuration = 10.0f;
CGPoint someOffscreenPos = ccp(-1024.0f, 512.0f);
// Move off screen, then remove yourself...
id asteroidMove = [CCMoveTo actionWithDuration:someDuration
position:someOffscreenPos];
id asteroidRemove = [CCCallBlock actionWithBlock:^
{
[asteroid removeFromParentAndCleanup:YES];
}];
id asteroidSeq = [CCSequence actions:asteroidMove, asteroidRemove, nil];
[asteroid runAction:asteroidSeq];
[self countDownToCreateNextAsteroid];
}
Therefore in your onEnter you could have something to kick it all off and that's it:
- (void)onEnter
{
[super onEnter];
// yada yada
[self countDownToCreateNextAsteroid];
}
And the rest would take care of itself. This assumes this quick and simple approach is all you were after. The count down method sets up the count down, calls a method to create an asteroid at the end of that time, then exits. After the asteroid is created a new call to the count down method is invoked, which will setup another asteroid to be created at another random time. This is one quick and simple way to do what it looks you are were actually trying to accomplish with all those timers.

Random Positioning issue

I am trying atm doing a game. I got some problems with the RandomPositioning with the blocks. With my code, the Blocks keep spawning at the same lane very fast. But thats not what I mean to. They should appear like a Mario Game. My Code:
HumanMovement = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:#selector(HumanMoving) userInfo:nil repeats:YES];
[self PlaceBlocks];
BlockMovement = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:#selector(BlockMoving) userInfo:nil repeats:YES];
}
-(void)BlockMoving{
StartingBlock.center = CGPointMake(StartingBlock.center.x -1, StartingBlock.center.y);
Block1.center = CGPointMake(Block1.center.x -1, Block1.center.y);
Block2.center = CGPointMake(Block2.center.x -1, Block2.center.y);
if ( Block1.center.x > 20) {
[self PlaceBlocks];
}
}
-(void)PlaceBlocks{
RandomBlock1Position = arc4random() %568;
RandomBlock1Position = RandomBlock1Position + 140;
RandomBlock2Position = RandomBlock2Position + 500;
Block1.center = CGPointMake(193 , RandomBlock1Position);
Block2.center = CGPointMake(280 , RandomBlock2Position);
}
So if i understood correctly your blocks should respawn once the reach the left side. In order to do so you have to change your center check position to :
if ( Block1.center.x < 20) {
[self PlaceBlocks];
}

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.

UIView Get Position during Animatoin

I have looked at every instance of this question on Stack as well as various other websites, its still not working out for me. I am trying to get the position of my object while the animation is in session.
Here is what I have:
- (void)viewDidLoad{
currentPosition = [[bikeMotion.layer presentationLayer] center]; //its a CGPoint
}
- (void)doAnimation {
bikeMotion = [[DotAnimation alloc]initWithFrame:CGRectMake((*bikePathPoints)[0].x, (*bikePathPoints)[0].y, 8, 8)];
//... [self animate stuff]...
[NSTimer scheduledTimerWithTimeInterval:0.07f target:self selector:#selector(backgroundAnimations) userInfo:nil repeats:YES];
}
-(void)backgroundAnimations{
cout << currentPosition.x << endl;
}
I also tried this:
- (void)viewDidLoad{
currentPosition = [[bikeMotion.layer presentationLayer] frame]; //its a CGRect
}
- (void)doAnimation {
bikeMotion = [[DotAnimation alloc]initWithFrame:CGRectMake((*bikePathPoints)[0].x, (*bikePathPoints)[0].y, 8, 8)];
//...[self animation stuff];
[NSTimer scheduledTimerWithTimeInterval:0.07f target:self selector:#selector(backgroundAnimations) userInfo:nil repeats:YES];
}
-(void)backgroundAnimations{
cout << currentPosition.origin.x << endl;
}
I have even tried this:
- (void)viewDidLoad{
p = (CALayer*)[bikeMotion.layer presentationLayer];
}
-(void)doAnimation{
bikeMotion = [[DotAnimation alloc]initWithFrame:CGRectMake((*bikePathPoints)[0].x, (*bikePathPoints)[0].y, 8, 8)];
[NSTimer scheduledTimerWithTimeInterval:0.07f target:self selector:#selector(backgroundAnimations) userInfo:nil repeats:YES];
}
-(void)backgroundAnimations{
CGPoint position = [p position];
cout << position.x << endl;
}
Have you tried object.layer.anchorpoint? You'll need to import QuartzCore.

Resources