2012-11-03 41 views
0

我正在用Cocos2d在Objective C中開發我的第一個應用程序。我是新來的目標c,但我試圖谷歌周圍,但我無法找到解決這個一般問題的解決方案。Cocos2d初學者objc_msg發送EXC_BAD_ACCESS

-(void)accelerate{ 
    moveSpeed = 720.0/3.0; 

    [self stopAllActions]; 
    _moving = FALSE; 
    CCAnimation *walkAnim = [CCAnimation animationWithFrames:_walkAnimFrames delay:0.066f]; 
    self.walkAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:walkAnim restoreOriginalFrame:NO]]; 
    CGPoint loc = ccp(500, 200); 
    [self playerMoveTo:loc]; 
} 

-(void)playerMoveTo:(CGPoint)moveLocation{ 
    CGPoint moveDifference = ccpSub(moveLocation, self.position); //here is EXC_BAD_ACCESS 
    float distanceToMove = ccpLength(moveDifference); 
} 

,這就是我所說PLAYER1從我的遊戲場景加速方式:

-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event { 
    CGPoint touchLocation = [touch locationInView: [touch view]]; 
    touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation]; 
    touchLocation = [self convertToNodeSpace:touchLocation]; 
    [self.Player1 accelerate]; 
} 

PLAYER1是我gameScene:

//implementation 
@synthesize Player1 = _Player1; 

//header 
@property (nonatomic,retain) TPlayer *Player1; 

感謝您的耐心和幫助。我不確定代碼的哪一部分應該放在這裏,所以請告訴我什麼,我會添加它。

西蒙

編輯1: PLAYER1在遊戲場景的初始化函數分配。 TPlayer是CCSprite的子類:

_Player1 = [[TPlayer alloc] initWithSpriteFrameName:@"walk2"]; 

而且EXC_BAD_ACCESS發生在這條線:

CGPoint moveDifference = ccpSub(moveLocation, self.position); 
+0

EXC_BAD_ACCESS在哪一行發生? –

+0

另外你在哪裏分配Player1 –

+0

我剛編輯它 – Simon

回答

0

由於內存問題,self.position可能會崩潰。自我可能會被釋放給你。你正在運行什麼版本的Xcode?在最新版本中,@synthesize是不必要的,因爲屬性會自動爲您合成。您也可以考慮將您的項目轉換爲ARC。我已經完成了我的Cocos2D項目,我很高興我做到了。

你可以嘗試:

_Player1 = [[[TPlayer alloc] initWithSpriteFrameName:@"walk2"] autorelease]; 

或手動初始化之後撞了引用計數:

[self.Player1 retain]; 

要看看是否有幫助。這就是我喜歡ARC的原因:)

+0

非常感謝你,就是這樣 – Simon

0
  • 性能應該與小寫字母開始(並駝峯格式)

  • 您在何處您@合成屬性,而不是實際分配實例的位置。

喜歡的東西:

_player1 = [[Player alloc] init]; 

很難說更沒有看到回溯和ccpSub()定義。最好的猜測是,self.position正在返回一個無意義的值,使ccpSub()走上軌道。 self不太可能是過度發佈的,但仍然可行,以允許隨後在調用[self position]時崩潰的方法調度。

+0

謝謝...但是我認爲它必須做一些事情,而不是清理內存。我意識到我可以在playerMoveTo中聲明只有一個變量。當我宣佈第二個失敗時......你對我有什麼小暗示我應該在哪裏尋找問題..? – Simon

0

你的解決方案現在崩潰了吧......但是你的moveTo函數是不正確的。

-(void)playerMoveTo:(CGPoint)moveLocation{ 
    CGPoint moveDifference = ccpSub(moveLocation, self.position); //here is EXC_BAD_ACCESS 
    float distanceToMove = ccpLength(moveDifference); 

    [self runAction:[CCMoveTo actionWithDuration:1 position:moveLocation]]; 

}