1

我在坦克底座顶部有一个炮塔,两者都在同一个精灵表内,并正确指定了框架。当我构建和运行项目时,我希望炮塔沿着坦克中心的锚点旋转。炮塔是坦克的一个孩子,因此它们在移动时会保持在一起。但是,当我尝试旋转它时,炮塔似乎将其锚点设置在远处的某个地方,如下所示:在此处输入图像描述在此处输入图像描述

这是我的初始化:

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

2 回答 2

0

Since the turret is a child of the tank, this:

 _turret.position = ccp(40, 50);

offsets the turret by 40x50 away from the tank's origin (lower left corner of bounding box). Try settings the position so the turret is centered on the tank:

 _turret.position = ccp(tank.contentSize.width * tank.anchorPoint.x,
                        tank.contentSize.height * tank.anchorPoint.y);
于 2012-07-16T17:40:31.417 回答
0

Hmm. The only thing that I think could be causing this is that the turret asset is not centered or has a lot of blank space. That said, I'd try playing with the anchor point of the turret.

于 2012-07-16T17:39:40.590 回答