-(void) registerWithTouchDispatcher
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:kCCMenuTouchPriority swallowsTouches:NO];
}
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
for (CCSprite *mole in moles) {
if (mole.userData == FALSE) continue;
if (CGRectContainsPoint(mole.boundingBox, touchLocation)) {
mole.userData = FALSE;
score+= 10;
[mole stopAllActions];
CCAnimate *hit = [CCAnimate actionWithAnimation:hitAnim restoreOriginalFrame:NO];
CCMoveBy *moveDown = [CCMoveBy actionWithDuration:0.2 position:ccp(0, -mole.contentSize.height)];
CCEaseInOut *easeMoveDown = [CCEaseInOut actionWithAction:moveDown rate:3.0];
[mole runAction:[CCSequence actions:hit, easeMoveDown, nil]];
}
}
#pragma mark - Adjusted Box
-(CGRect)adjustedBoundingBox {
// Adjust the bouding box to the size of the sprite
// without the transparent space
CGRect vikingBoundingBox = [self boundingBox];
float xOffset;
float xCropAmount = vikingBoundingBox.size.width * 0.5482f;
float yCropAmount = vikingBoundingBox.size.height * 0.095f;
if ([self flipX] == NO) {
// Viking is facing to the rigth, back is on the left
xOffset = vikingBoundingBox.size.width * 0.1566f;
} else {
// Viking is facing to the left; back is facing right
xOffset = vikingBoundingBox.size.width * 0.4217f;
}
vikingBoundingBox =
CGRectMake(vikingBoundingBox.origin.x + xOffset,
vikingBoundingBox.origin.y,
vikingBoundingBox.size.width - xCropAmount,
vikingBoundingBox.size.height - yCropAmount);
if (characterState == kStateCrouching) {
// Shrink the bounding box to 56% of height
// 88 pixels on top on iPad
vikingBoundingBox = CGRectMake(vikingBoundingBox.origin.x,
vikingBoundingBox.origin.y,
vikingBoundingBox.size.width,
vikingBoundingBox.size.height * 0.56f);
}
return vikingBoundingBox;
}return TRUE;}
本文介绍了如何在 Cocos2d-x 中注册触摸事件并实现精灵之间的碰撞检测。通过调整精灵的 bounding box 大小来更精确地匹配精灵的实际可见区域,从而提高碰撞检测的准确性。
2021

被折叠的 条评论
为什么被折叠?



