如何让CCSprite跟随用户与ccTouchMoved联系

时间:2011-03-21 10:40:38

标签: objective-c xcode cocos2d-iphone ccsprite

我希望能够在用户触摸的情况下移动某些精灵图像。 这些方面的东西:

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    for (UITouch *touch in touches)
    {
        CGPoint *location = [touch locationInView:[touch view]];
        location = [[CCDirector sharedDirector] convertToGL: location];
        if (CGRectContainsPoint(sprite.boundingBox, location)
        {
            sprite.location = ccp(location.x, location.y);
        }
    }
}

当然,这对我来说不起作用,因为没有为此方法运行的tick方法来连续移动CCSprite。我知道ccTouchMoved的方法,但我不确定如何实现它,任何例子都会非常感激。

3 个答案:

答案 0 :(得分:4)

只有CClayer能够检测到触摸,它是自动的。因此,您将需要处理每个蜱事件。它应该是ccTouchesMove ..类似于:

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"begin");
}

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{    
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView: [touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];

    sprite.position = location;
}

-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"Ended");
}

当然,在您的init中,您必须设置self.isTouchEnabled = YES;

答案 1 :(得分:2)

您可以在场景中使用以下方法拖动精灵图像:

-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint location = [self convertTouchToNodeSpace: touch];
    sprite.position = location;
}

答案 2 :(得分:1)

请根据以下代码修改您的代码,这对我有用。

UITouch * touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
if (CGRectContainsPoint(sprite.boundingBox,location)){
    [sprite setPosition:location];

}