2011-06-09 38 views
1

原諒我的基本問題,因爲我對cocos2d很新,但我有一個問題移動一個精靈周圍。該方法似乎做我想要的...只要它在正X和正Y方向(右上角)移動。如果我嘗試將其向下或向左移動,則不起作用。cocos2d ccTouchesMoved只移動精靈到右上角

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    UITouch *myTouch = [touches anyObject]; 
    CGPoint point = [myTouch locationInView:[myTouch view]]; 
    point = [[CCDirector sharedDirector] convertToGL:point]; //create point location 
    CCNode *sprite = [self getChildByTag:kTagSprite]; //set sprite 
    CGRect spriteRect = CGRectMake(sprite.position.x, sprite.position.y, sprite.contentSize.width, sprite.contentSize.height); //create box around sprite and get position 
    if(CGRectContainsPoint(spriteRect, point)){ 
     [sprite setPosition:point]; //if my pointer is inside of the sprite box, move the sprite 
    } 
} 

謝謝。

編輯:加入我的init和標籤參考

-(id) init{ 
    if((self = [super init])){ 
     self.isTouchEnabled = YES; 
     CCSprite *mySprite = [CCSprite spriteWithFile:@"sprite.png"]; 
     mySprite.position = ccp(240, 40); 
     [self addChild:mySprite z:0 tag:kTagSprite]; 
    } 
    return self; 
} 

,我宣佈kTagSprite在:

enum{ 
    kTagSprite 
}; 
+0

你是如何創建背後的對象kTagSprite?向我們展示代碼..如何在init中加載精靈? – cocos2dbeginner 2011-06-09 15:30:23

+0

編輯問題。感謝您的期待。 – 2011-06-09 15:35:03

回答

0
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    UITouch *myTouch = [touches anyObject]; 
    CGPoint point = [myTouch locationInView:[myTouch view]]; 
    point = [[CCDirector sharedDirector] convertToGL:point]; //create point location 
    CCSprite *sprite = [self getChildByTag:kTagSprite]; //set sprite 

    if(CGRectContainsPoint([sprite boundingBox], point)){ 
     [sprite setPosition:point]; //if my pointer is inside of the sprite box, move the sprite  CCLOG(@"THIS WILL BE CALLED"); 
    } 
} 

運行代碼,並期待在控制檯,看看日誌會被稱爲..

+0

至於你的建議的最重要部分,控制檯只有在if語句中,如果對象向上或向右移動或兩者的混合,纔會達到。點擊該對象或將其向下和/或向左移動,它不會到達if語句內部。然而,使用你的第二塊代碼,everythign工作得很好!非常感謝你。我不知道那個boundingBox選項。 – 2011-06-09 15:54:56

+0

:)............... – cocos2dbeginner 2011-06-09 16:20:26