cocos2d ccTouchesMoved仅将精灵移动到右上角

时间:2011-06-09 15:27:01

标签: cocos2d-iphone touch cgrect

请原谅我的基本问题,因为我对cocos2d很陌生,但我有一个问题就是移动精灵。这种方法似乎做了我想要的......只要它在正x和正y方向(右上角)移动。如果我试图将其向下移动或向左移动,则不起作用。

-(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
};

1 个答案:

答案 0 :(得分: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");
    }
}

运行代码并查看控制台以查看是否将调用日志..