Building a Simple Game with Cocos2d-x
Adding a Sprite
To display a graphical element on the screen, initialize a Sprite object, define its coordinates, and attach it to the active scene layer.
auto playerSprite = Sprite::create("PlayerGraphic.png");
if (!playerSprite) {
return;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
playerSprite->setPosition(Vec2(playerSprite->getContentSize().width / 2.0f, visibleSize.height / 2.0f));
this->addChild(playerSprite);
Sprite Movement and Actions
Animating sprites requires binding Action objects. Time-based transitions utilize ActionInterval, while immediate responses rely on ActionInstant. A common pattern involves spawning an adversary, defining a traversal path, and scheduling a cleanup callback upon completion.
void GameScene::spawnEnemy() {
auto adversarySprite = Sprite::create("EnemyGraphic.png");
auto screenBounds = Director::getInstance()->getVisibleSize();
float lowerBound = adversarySprite->getContentSize().height / 2.0f;
float upperBound = screenBounds.height - lowerBound;
float spawnY = lowerBound + (upperBound - lowerBound) * CCRANDOM_0_1();
adversarySprite->setPosition(Vec2(screenBounds.width + adversarySprite->getContentSize().width / 2.0f, spawnY));
this->addChild(adversarySprite);
float traversalDuration = 2.0f + CCRANDOM_0_1() * 2.0f;
auto movementEndpoint = Vec2(-adversarySprite->getContentSize().width / 2.0f, spawnY);
auto trajectoryAction = MoveTo::create(traversalDuration, movementEndpoint);
auto removalCallback = CallFuncN::create(CC_CALLBACK_1(GameScene::removeNode, this));
adversarySprite->runAction(Sequence::create(trajectoryAction, removalCallback, nullptr));
}
Handling Touch Input
Screen interactions are captured by configuring an event listener for the scene graph. Override the touch termination method to extract and manipulate the exact coordinates of the user's tap.
// Registering the listener
auto touchListener = EventListenerTouchOneByOne::create();
touchListener->onTouchEnded = CC_CALLBACK_2(GameScene::processTouchEnd, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
// Processing the input
void GameScene::processTouchEnd(Touch* touchData, Event* eventType) {
Vec2 interactionPoint = touchData->getLocation();
// Execute logic based on interactionPoint coordinates
}
Playing Sound Effects
Audio feedback enhances user experience. Trigger short audio clips instantly during specific game events, such as firing a projectile.
AudioEngine::play2d("laser_fire.wav");