2011-06-09 63 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