当我触摸屏幕时,我的精灵必须改变

时间:2011-04-03 18:53:35

标签: xcode cocos2d-iphone

我正在尝试开发一个动作而我无法获得这个效果:

当我触摸屏幕时,我的精灵必须换另一个,当我挂起时它必须回到初始状态。如何检测触摸屏幕并更改精灵的时间?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

使用变量normalSprite和pressedSprite创建CCNode的子类。在初始化程序中,添加它以便它处理触摸:

[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];

添加一个带有此签名的方法,以便在触摸屏幕时进行处理:

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    // Check that touch is within boundaries of this object
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
    if (!CGRectContainsPoint(CGRectMake(0, 0, self.boundingBox.size.width, self.boundingBox.size.height), touchLocation)) {
        return TRUE;
    }
    // Switch image
    [self removeChild:normalSprite cleanup:NO];
    [self addChild:pressedSprite];

    return TRUE;
}

添加一个带有此签名的方法来处理手指何时熄灭:

-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    // Switch image back
    [self removeChild:pressedSprite cleanup:NO];
    [self addChild:normalSprite];
}

您还可以添加ccTouchMoved(其他所有内容与ccTouchEnded相同),以处理触摸移动到对象边界内外的情况。