Wednesday, January 20, 2016

Cocos2d-x C++ Create Sprite

Sprite is a 2d image that must have in game development, therefore, sprite can be change their properties such as change color, move or even animating. In this tutorial will show how to create sprite and positioning sprite.

1. Open ide
2. Open HelloWorldScene.cpp
3. In HelloWorldScene.cpp class under bool HelloWorld::init() function, below if statement, enter code below. i.e.
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
//////////////////Start your coding here
return true;
}

To create sprite simply add this code;
auto spriteName = Sprite::create("spritename.png");

Positioning the sprite
spriteName->setPosition(Vec2(50,50));
setPosition properties represent setPosition(Vec2(x,y)). x and y will represent coordinate of the screen.

Adding sprite to screen
this->addchild(spriteName);

The code should be like this;
auto spriteName = Sprite::create("spritename.png");
spriteName->setPosition(Vec2(winSize.width/2, winSize.height/2));
this->addchild(spriteName);

Positioning sprite center of the screen add this code;
auto winSize = Director::getInstance()->getWinSize();
Function of the code above is to get the screen size position

The code should be like this;
auto winSize = Director::getInstance()->getWinSize();

auto spriteName = Sprite::create("spritename.png");
spriteName->setPosition(Vec2(winSize.width/2, winSize.height/2));
this->addchild(spriteName);

0 comments:

Post a Comment