精灵不能正确旋转(cocos2d)

时间:2012-07-16 17:36:08

标签: iphone cocos2d-iphone rotation sprite

我在坦克底座上有一个炮塔,两个都在同一个精灵表内,正确指定了框架。当我建造并运行该项目时,我希望炮塔沿着坦克中心的锚点旋转。炮塔是坦克的孩子,因此它们在移动时会保持在一起。然而,当我尝试旋转它时,炮塔似乎将其锚点设置在远处的距离,如下所示:enter image description here enter image description here

这是我的初学者:

- (id)initWithLayer:(HelloWorldLayer *)layer type:(int)type hp:(int)hp {

NSString *spriteFrameName = [NSString stringWithFormat:@"tank%d_base.png", type];    
if ((self = [super initWithSpriteFrameName:spriteFrameName])) {
    _layer = layer;
    _type = type;
    self.hp = hp;
    _turret = [CCSprite spriteWithSpriteFrameName:[NSString stringWithFormat:@"tank%d_turret.png", type]];
    _turret.anchorPoint = ccp(0.5, 0.25);
    [self scheduleUpdateWithPriority:-1];
    [self addChild:_turret];
     _turret.position = ccp(40, 50);
}

return self;
}

我在这里旋转精灵(我使用360度射击范围)

- (void)shootToward:(CGPoint)targetPosition {

//CGPoint offset = ccpSub(targetPosition, self.position);
float x = abs(targetPosition.x) - self.position.x;
float y = abs(targetPosition.y) - self.position.y;
float angle;
float angleDegrees;
if (x < 0 && y > 0) {
    angle = atanf(y/x);
    angleDegrees = -CC_RADIANS_TO_DEGREES(angle) - 90;
}
else if (x < 0 && y < 0) {
    angle = atanf(y/x);
    angleDegrees = -CC_RADIANS_TO_DEGREES(angle) - 90;
}
else if (x > 0 && y < 0) {
    angle = atanf(y/x);
    angleDegrees = 90 - CC_RADIANS_TO_DEGREES(angle);
}
else if(x > 0 && y > 0) {
    angle = atanf(y/x);
    angleDegrees = 90 - CC_RADIANS_TO_DEGREES(angle);
}
switch (_layer.rotateInt) {
    case 0:
        angleDegrees = angleDegrees;
        break;
    case 1:
        angleDegrees = angleDegrees+ 180;
        break;
    case 2:
        angleDegrees = angleDegrees;
        break;
    case 3:
        angleDegrees = angleDegrees + 90;
        break;
    case 4:
        angleDegrees = angleDegrees - 90;
        break;
    default:
        break;
}

NSLog(@"%f",angleDegrees);
_turret.rotation = angleDegrees;

2 个答案:

答案 0 :(得分:0)

嗯。我认为唯一可能造成这种情况的是炮塔资产不居中或有很多空白。也就是说,我会试着玩炮塔的锚点。

答案 1 :(得分:0)

由于炮塔是坦克的孩子,所以:

 _turret.position = ccp(40, 50);

将炮塔偏离油箱原点40x50(边界框的左下角)。尝试设置位置,使炮塔位于油箱的中心位置:

 _turret.position = ccp(tank.contentSize.width * tank.anchorPoint.x,
                        tank.contentSize.height * tank.anchorPoint.y);