2014-02-26 32 views
0

我正在製作一個涉及在屏幕上從左到右移動的太空船的iPhone遊戲。我想這樣做,只有按下按鈕,船隻纔會移動。這是我創建移動的當前代碼,但當按鈕不再按下時,它不會停止。COCOS2d創建按鈕時的動作

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    CGSize winSize = [CCDirector sharedDirector].winSize; 

NSSet *allTouches = [event allTouches]; 
UITouch *touch = [allTouches anyObject]; 
CGPoint location = [touch locationInView:[touch view]]; 
location = [[CCDirector sharedDirector] convertToGL:location]; 

if (CGRectContainsPoint([_paddle2 boundingBox], location)){ 
    int bottomOfScreenX = 0 + _Paddle1.contentSize.width/2; 
    id action = [CCMoveTo actionWithDuration:5 position:ccp(bottomOfScreenX,winSize.height/3) ]; 
    [_starShip runAction:action]; 
    [action setTag:1]; 

} 

}

-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event 
{ 
    [_starShip stopActionByTag:1]; 
} 
+1

我個人不會打擾CCMoveTo。在按下按鈕時更新太空船的位置,並沿x軸遞增。一旦按鈕不再被按下停止遞增。 –

回答

0

與此代碼的問題是,TouchHasEnded和TouchHasBegan各自使用不同的參數設置器。當TouchEnded正在起訴UITouch時,Touch開始使用NSSet。將TouchHasEnded設置爲

- (void)ccTouchEnded:(NSSet *)接觸事件:(UIEvent *)事件;

具有觸摸開始

- (空)ccTouchBegan:(UITouch *)觸摸withEvent:方法(*的UIEvent)事件。

第二種方法需要稍微調整邏輯。

1

我相信它與你使用「ccTouchesBegan」和「ccTouchEnded」一起使用。通知「觸及」與「觸摸」。他們需要保持一致。 ccTouchesBegan處理多個觸摸事件,而ccTouchBegan僅用於單點觸摸事件。因此,看起來你正在處理一個觸摸事件,你真的不需要使用ccTouchesBegan。切換到ccTouchBegan,你應該沒問題。