gpt4 book ai didi

objective-c - 旋转、缩放 Cocos2d 继承层,以 2 个 Sprite 作为子级

转载 作者:行者123 更新时间:2023-11-29 04:52:35 25 4
gpt4 key购买 nike

开门见山,我有一个类,它基本上继承自 CCLayer,并且有 2 个 Sprite 作为子级。

some_layer.h

@interface some_layer : CCLayer {
CCSprite *back;
CCSprite *front;
}

some_layer.mm

// on "init" you need to initialize your instance
-(id) init
{
if( (self=[super init])) {
back = [CCSprite spriteWithFile:@"back.png"];
front = [CCSprite spriteWithFile:@"front.png"];
[front setOpacity:0];
[self addChild:back];
[self addChild:front];
//this is after modification
back.positionInPixels = CGPointMake(winSizeInPixels.width/2,winSizeInPixels.height/2);
front.positionInPixels = CGPointMake(winSizeInPixels.width/2,winSizeInPixels.height/2);

}
return self;

}
//after the edit
-(void) setPositionInPixels:(CGPoint)positionInPixels {
[super setPositionInPixels:CGPointMake(positionInPixels.x -(winSizeInPixels.width/2), positionInPixels.y -(winSizeInPixels.height/2))];
}

-(void) setPosition:(CGPoint)position {
[super setPosition:CGPointMake(position.x -(winSize.width/2), position.y -(winSize.height/2))];
}

当然,这并不是该层的全部实现,但该代码是与问题相关的唯一代码,如果您认为需要更多代码,请告诉我。

现在在父层的某些部分我正在尝试执行此操作

    float x = winSizeInPixels.width/2;
float y = winSizeInPixels.height/2;
[self setPositionInPixels:CGPointMake(x, y)];
mylayer = [[some_layer alloc] init];
[mylayer setPositionInPixels:CGPointMake(-offset, -offset)];
[self addChild:mylayer];
[mylayer runAction:[CCEaseInOut actionWithAction:[CCRotateTo actionWithDuration:speed*20 angle:angle] rate:4]];

这段代码的输出是,我可以看到 Sprite 旋转,但不是围绕 some_layer 的中心旋转,我希望它们旋转并保持在原来的位置(围绕它们自己旋转),我想做的是旋转,同时缩放它们,同时保持它们在屏幕上的位置相同,

Sprite 保持围绕某个随机点旋转(可能围绕其父级的父级,在最后的代码中是 self )

顺便说一句,我没有触摸 Sprite 的前后位置,我只处理“some_layer”,我尝试将它们的位置设置为(0,0)

“some_layer”的位置唯一正确的是当它的旋转角度为0,其比例为1.0时,如果有不清楚的地方请告诉我,非常感谢,我可以提供一些屏幕截图

编辑:我修改了上面的代码,它作为一种解决方法可以正常工作,但我认为这不是正确的方法!请查看评论,我不知道发生了什么奇怪的事情!!

谢谢!

编辑 2:找到答案

回答我自己

将其添加到 some_layer.mm 的 init 方法中

[self setContentSize:CGSizeMake(0, 0)];

感谢所有试图帮助我的人:)

分析代码是最好的解决方案!

顺便说一句,我删除了 setPos 的重写方法,并删除了更改 Sprites 位置的代码,现在就像这样

// on "init" you need to initialize your instance
-(id) init
{
if( (self=[super init])) {
back = [CCSprite spriteWithFile:@"back.png"];
front = [CCSprite spriteWithFile:@"front.png"];
[front setOpacity:0];
[self addChild:back];
[self addChild:front];
[self setContentSize:CGSizeMake(0, 0)];
}
return self;

}

最佳答案

您是否为您正在使用的图层或 Sprite 设置一些 anchor ?如果是,请检查 anchor 是否应设置在中心:

someSprite.anchorPoint=ccp(0.5,0.5);

了解更多详情:http://www.qcmat.com/understanding-anchorpoint-in-cocos2d/

关于objective-c - 旋转、缩放 Cocos2d 继承层,以 2 个 Sprite 作为子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8573058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com