我正在写下面的代码到xcode,它不断出现大小未声明:在这个函数中首次使用我如何修复这个,这样我就可以运行代码?
// on "init" you need to initialize your instance
-(id) init
{ CCSprite *spaceCargoShip = [CCSprite
spriteWithFile:@"spaceCargoShip.png"];
[spaceCargoShip setPosition:ccp(size.width/2, size.height/2)];
[self addChild:spaceCargoShip];
没有在该函数中声明size
变量。你必须从其他地方得到它-也许self.size
,但没有看到其余的代码,我不知道它应该来自哪里。
我猜你想把你的货船放在屏幕的左下角。为此,你需要使用你所创建的精灵的大小,即spaceCargoShip.contentSize.
不是[spaceCargoShip setPosition:ccp(size.width/2, size.height/2)];
使用[spaceCargoShip setPosition:ccp(spaceCargoShip.contentSize.width/2,
spaceCargoShip.contentSize.height/2)];
玩得开心!
我也有同样的问题。
代码必须放在init
函数和if
语句中。
- (id)init {
if (self = [super init]) {
//Code for the spaceCargoShip
...
// ask director the the window size
CGSize size = [[CCDirector sharedDirector] winSize]; //<-- This is the "size" variable that the code is looking for.
...
//Enter the code for the spaceCargoShip in here.
CCSprite *spaceCargoShip = [CCSprite spriteWithFile:@"SpaceCargoShip.png"];
[spaceCargoShip setPosition:ccp(size.width/2, size.height/2)];
[self addChild:spaceCargoShip];
}
return self;
}
它不起作用的原因是,如果你不把它放在if statement
中,变量就会超出作用域。