I am pretty new to C++ and cocos2d-x, so the answer could be something very simple, but for the life of me I can't figure out why it's acting like this.
Below is a relevant snippet, modified/simplified version of HelloWorldScene.cpp
:
bool PlayGame::init()
{
if ( !Layer::init() ) return false;
double startX = this->getBoundingBox().getMidX() / 3;
double startY = this->getBoundingBox().size.height * 0.95;
Sprite* sprite = Sprite::create( "sprite.png" );
sprite->setPosition( startX, startY );
this->addChild( sprite );
return true;
}
Now my code works perfectly as intended, but if I were to define startX
and startY
before the line that checks if the CCLayer
has initialized properly, they return (0, 0)
instead of somehwere in the top left corner. My guess is that, before the line if ( !Layer::init() )
, the PlayGame
layer has not been initialized and therefore have a size of 0
.
But as far as I'm concerned, that line is only responsible for checking whether the layer has initialized without a problem, and the actual initialization is triggered by the create()
method called inside the definition of the parent CCScene
. So I thought the size of the layer should have been initialized anywhere inside the function block.
What am I missing here?
The PlayGame::create()
function in createScene()
, which would look something like this in your case
Scene* PlayGame::createScene()
{
auto scene = Scene::create();
auto layer = PlayGame::create(); // this one right here constructs the Layer and triggers PlayGame::init()
scene->addChild(layer);
return scene;
}
is responsible for calling your PlayGame::init()
function. However, the static Layer::init()
, which sets the content size, must be explicitly called before you set or get any Layer
-related members in init()
.
Here's the implementation of Layer::init()
directly extracted from the library
bool Layer::init()
{
Director * director = Director::getInstance();
setContentSize(director->getWinSize()); // this is the line that needs to be executed before you set anything
return true;
}