2011-06-06 112 views
0

我用cocos2d編寫了幾款遊戲,但它們都是由加速度計控制的,並且只使用簡單的觸摸事件。我需要做的就是在任何地方觸摸屏幕時進行註冊。我不需要關於位置或速度的任何信息。角色目前在屏幕上移動,用戶應該能夠觸摸角色以使角色在屏幕上移動。當前的代碼不能按預期工作。角色不受觸摸影響,它只是繼續向下移動屏幕。請指教。以下是我現在嘗試使用的代碼。Cocos2d iPhone遊戲觸摸屏讓角色移動

在遊戲更新方法:

if (IsTouched == TRUE) { 
    SealPositionBasedOnTouchInt = SealPositionBasedOnTouchInt - (100*dt); 
} 

else { 
    SealPositionBasedOnTouchInt = SealPositionBasedOnTouchInt + (100*dt); 
} 

SealSwimming.position = ccp(SealPositionBasedOnTouchInt, SealSwimming.position.y); 

觸摸事件:

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 


    for(UITouch *touch in touches) 
    { 
    CGPoint location = [touch locationInView: [touch view]]; 
    location = [[CCDirector sharedDirector] convertToGL: location]; 
    IsTouched = TRUE; 
} 
} 

你會發現我得到的觸摸位置,這是當前未使用的任何東西,但就是在樣品。

回答

0

你重寫:

-(void) registerWithTouchDispatcher { 
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES]; 
} 
在層

/節點正在接收觸摸?

您也可以嘗試撥打您的代碼addTargetedDelegate:self而不是覆蓋registerWithTouchDispatcher,但我從來沒有嘗試過。

1

確保層已啓用觸摸事件isTouchEnabled

+0

天哪,多麼愚蠢的錯誤。有時幫助其他人看看它。就是這樣,我沒有在init方法中啓用touch。謝謝!! – user597136 2011-06-06 13:38:04

+0

沒問題!我們都這樣做! – 2011-06-06 13:39:53

0

塞爾吉奧已經回答了你的問題,倒是不登記。我最近有一個類似的問題。如果用戶觸摸屏幕的位置並不重要,那麼swallowsTouches:YES很好,但如果您有多個需要註冊觸摸的圖層,則可能需要將其設置爲NO。

0

我還沒有測試過這個。

in .h 

CCSprite *sprite; 


in .m 

-(id)init 
{ 
    if ((self=[super init)) 
    { 
      CGSize s = [[CCDirector sharedDirector] winSize]; 

      sprite = [CCSprite spriteWithFile:@"imagename.png"]; 
      sprite.position = ccp(s.width/2, s.height/2); 
      [self addChild:sprite]; 
    } 
    return self; 
} 

    - (void) ccTouchesBegan: (NSSet *)touches withEvent: (UIEvent *)event 
{ 

    UITouch *touch = [touches anyObject]; 

    CGPoint touchLocation = [touch locationInView: [touch view]]; 
    touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation]; 

    [sprite setPosition:touchLocation]; 

    //OR YOU CAN RUN AN ANIMATION TO MAKE IT LOOK LIKE IT'S WALKING 
    //[sprite runAction:[CCMoveTo actionWithDuration:5 position:touchLocation]]; 
}