Monday, January 19, 2015

[Tutorial] Cocos2d-x: Create the first simple game - Touch screen event and shoot bullets (Part 2)

In part 1, we studied how to create a character, and monsters from images through class Sprite. And in adding monsters, you notice a block calculating the appearing position, and the moving speed. It's the simple algorithm.

In this part, we do some following tasks:

+ Catch event when touching screen
+ When touching screen, our character will shoot
+ Process the direction of the bullet flying following the point when touching

Let's Start!

Step 1 - touchscreen event and how to detect

You open file HelloWorldScene.cpp, in function init() find to the end of the function before return true; add the following block:

//Create an object to dispatch event information
auto dispatcher = Director::getInstance()->getEventDispatcher();
//Create an object to listen to touchscreen event follow One by One way
auto listener1 = EventListenerTouchOneByOne::create();
//Set swallow for Touch event when happening, prevent not allow objects catching other events using this event
listener1->setSwallowTouches(true);

//Catch Touch event, when Touch event happens, call corresponding function of HelloWorld class
listener1->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
listener1->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this);
listener1->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this);

//Send to dispatcher to process
dispatcher->addEventListenerWithSceneGraphPriority(listener1, this);

return true;

* Notice: Although not using onTouchMoved, but we should make Touch event be processed completely.

Step 2 - Process touch event - create the ability to shoot bullets for character

Open file HelloWorldScene.h, add three more prototype functions:

void onTouchEnded (cocos2d::Touch* touches, cocos2d::Event* event);
void onTouchMoved (cocos2d::Touch* touches, cocos2d::Event* event);
//Notice: onTouchBegan must return bool
bool onTouchBegan (cocos2d::Touch* touches, cocos2d::Event* event);

Then open file HelloWorldScene.cpp to define these three functions.

Although we don't use all three functions, but for Touch event to process completely, you must declare all three functions as follow:


bool HelloWorld::onTouchBegan(Touch* touch, Event* event)

{  

return true; // must return True

}



void HelloWorld::onTouchMoved(Touch* touch, Event* event)
{  

// Not process here

}

void HelloWorld::onTouchEnded (Touch* touches, Event* event){
   
// Get coordinator of touch point
Point location =  touches->getLocationInView();
location = Director::getInstance()->convertToGL(location);

Size winSize = Director::getInstance()->getWinSize();

//Create a bullet as a Sprite, set first position for main character
auto projectile = Sprite::create("Projectile.png");
projectile->setPosition( Point(20, winSize.height/2) );

// This block calculates the end point of the bullet through the first position and the position on Touch, the below picture can demonstrate for this. Here apply some basic formula of math. 

// Coordinator of touch point subtract coordinator of the top of bullet (offX, offY)
int offX = location.x - projectile->getPosition().x;
int offY = location.y - projectile->getPosition().y;

// Not allow to shoot reversely and shoot straightly to the bottom ( below the character )

if (offX <= 0) return;

// If the above condition is satisfied, create the shape of bullet on the screen
this->addChild(projectile,1);

//Calculate the coordinator of the end point through the coordinator of the beginning point and the distance offX, offY
// The absolute coordinate realX = screen width + 1/2 bullet width, just right on flying out of screen
int realX = winSize.width  + (projectile->getContentSize().width/2); 

// The ratio between offY and offX
float ratio = (float)offY / (float)offX;

// The absolute coordinator of realY can be calculated based on realX and the above ratio + the beginning coordinator Y of the bullet ( calculate follow Talet in triangle, or follow tang of angle)

int realY = (realX * ratio) + projectile->getPosition().y; // must be: int realY = ((realX-projectile->getPosition().x) * ratio) + projectile->getPosition().y; (realX-projectile->getPosition().x is exactly the length from beginning point to end point on X axis

//The coordinator of end point
auto realDest = Point(realX, realY);

//The length of distance of bullet, calculate follow Pitago a*a = b*b + c*c, a is the subtense of square triangle
int offRealX = realX - projectile->getPosition().x;
int offRealY = realY - projectile->getPosition().y;
float length = sqrtf((offRealX * offRealX)  + (offRealY*offRealY));

// Set the velocity 480 pixels per second
float velocity = 480/1;

// The duration that bullet fly = the distance that bullet fly divide by the above velocity
float realMoveDuration = length/velocity;

// Move the bullet to end point with the time and the coordinate that calculated above. When go through the edge of the screen, it will disappear
projectile->runAction( Sequence::create(
MoveTo::create(realMoveDuration, realDest),
CallFuncN::create(CC_CALLBACK_1(HelloWorld::spriteMoveFinished,this)), NULL) );

}

The code block runAction seems to be complex but if written explicitly, it will be as follow:

//Move bullet with time and coordinator that calculated above
auto move= MoveTo::create(realMoveDuration,realDest);

//When move to the end poing, you will call the function spriteMoveFinished to remove the image of bullet, if not remove, the bullet fly out but still in the Layer, more and more, and process much more. This block will return an Action*
auto finish=CallFuncN::create(CC_CALLBACK1(HelloWorld::spriteMoveFinished,this));

//Perform in sequence two tasks, Move and then Delete
auto run = Sequence::create(move,finish,NULL);

//Perform the task of processing Sequence
projectile->runAction(run);

You should review the lesson Basic Actions of Sprite

Here is the image that demonstrate the calculation of the flying distance of bullet



Posted By Live Blog8:57 AM

[Tutorial] Cocos2d-x: Create the first simple game - Create a character (Part 1)

Now we will start making a simplest game. This game in old version here ( for Cocos2d-x V2.2.3)

Describe a bit about this game as follow: We have a main character and a lot of monsters, main character will kill monsters by shooting them. The game will calculate score simply (one monster killed provide you one point), and also have GameOver, you can insert music if need.

Let's go!

Step 1 - Create Project, add Resource images, sounds etc.

First, you must create a new Project (using cmd). Using command line on any platforms ( WIN, MAC, LINUX) are the same.

>cocos new firstgame -p com.vn.firstgame -l cpp -d E:/android/project

You need to download Resource ( image files ) and copy overwrite into Resource folder of Project firstgame. If you build for Android, you copy into Resource in folder proj.android of firstgame. Resource Here

Step 2 - Create character

It seems huge, but only add a Sprite of image into Layer. You do as follow:

1/ Main character
In function bool HelloWorld::init(), you delete all but following block

    if ( !Layer::init() )
    {
        return false;
    }
    
----Delete
----Delete

return true;

Then add before return true; the following block:
// Get the screen size
Size winSize = Director::getInstance()->getWinSize(); 
// Create a Sprite, our character
auto player = Sprite::create("Player.png");
// Set on the left of the screen
player->setPosition( Point(player->getContentSize().width/2, winSize.height/2) );
// Add into layer in the Scene game
this->addChild(player,1);
// Call function gameLogic , this function has task to create monsters with the speed one monster per second.
this->schedule( schedule_selector(HelloWorld::gameLogic), 1.0 );

2/ Create monsters

You open file HelloWorld.h and add 3 prototype functions:

void addTarget();  
void gameLogic(float dt);
void spriteMoveFinished(cocos2d::Node* sender);

Then you must declare these functions in HelloWorld.cpp as follow:

*
void HelloWorld::gameLogic(float dt)
{
    this->addTarget();
}

**

// This function creates mosnters and move them
void HelloWorld::addTarget()
{
    auto target = Sprite::create("Target.png");
    Size winSize = Director::getInstance()->getWinSize();
// This block calculates the area monsters appear in the place that not hidden out of the screen edge

    int minY = target->getContentSize().height/2;
    int maxY = winSize.height
                          -  target->getContentSize().height/2;
    int rangeY = maxY - minY;
    int actualY = ( rand() % rangeY ) + minY;
//
// Set monsters into above actualY (random)
    target->setPosition(Point(winSize.width + (target->getContentSize().width/2),actualY));
    this->addChild(target,1);

 //Calculate the speed for monsters to move
    int minDuration = (int)2.0;
    int maxDuration = (int)4.0;
    int rangeDuration = maxDuration - minDuration;
    int actualDuration = ( rand() % rangeDuration )
                                        + minDuration;
// Move monsters with the speed within actualDuration, from appearing point to Point(0,y)

auto actionMove =  MoveTo::create( (float)actualDuration, Point(0 - target->getContentSize().width/2, actualY) );

// Stop the moving of monsters when reaching the end poing
 auto actionMoveDone =   CallFuncN::create(CC_CALLBACK_1(HelloWorld::spriteMoveFinished,this));
/
// Run 2 above Action in sequence way by following command:
 target->runAction( Sequence::create(actionMove, actionMoveDone, NULL) );
}

You can refer Sprite and basic Action commands in previous lesson.

***
void HelloWorld::spriteMoveFinished(Node* sender)
{
// This function is only to remove Target ( being Sprite) from layer of game
// Cast to pointer Sprite of a Node*
  auto sprite = (Sprite *)sender;
  this->removeChild(sprite, true);    
}

Step 3 - Run
OK, now you can build and run on Windows with following command

>cocos run -s E:/android/project/firstgame -p win32

Here is the result!



Posted By Live Blog12:15 AM

Saturday, January 17, 2015

[Tutorial] Cocos2d-x: Menu, from basic to advanced

Now, let's start. Create a new Project named Menu as follow, using cmd 

>cocos new menu -p com.vn.menu -l cpp -d f:android/project

After new Project is created, you should run this command

>cocos compile -s f:android/project/menu -p win32


This is the first compile, purpose is linking to libraries in Engine. The first time to compile is so long. The next compile will be much faster because we only change some in Class and Resource.

Step 1) Copy code and run
You open Classes folder as following path E:/android/project/menu/Classes with 4 familiar files. But here we won't use class HelloWorldScene but replace by 2 other classes: MenuLayer and SceneManger.

You delete 2 files HelloWorldScene.cpp and HelloWorldScene.h, download source files Here and copy 4 files in zip file into Classes folder. And then you open file AppDelegate.cpp, in the second line #include you replace HelloWorldScene.h by  SceneManager.h, 
Delete the line auto scene = HelloWorld::createScene();
and director->runWithScene(scene); Ä‘i nhé. 
Add the following command SceneManager::goMenu(); into under the two above lines

Done, before compiling and running you open file Menu.vcxproj as following path E:/android/project/menu/proj.win32/ and find "HelloWorldScene.cpp" You will see 4 files here when compiled (HelloWorldScene.h, HelloWorldScene.cpp, AppDelegate.cpp, AppDelegate.h )

Because you deleted files HelloWorldScene.h and HelloWorldScene.cpp so here you delete too. And add 4 files SceneManager.h, SceneManager.cpp, MenuLayer.h , MenuLayer.cpp into Menu.vcxproj for compiler to process these 4 files when we compile again to run, as follow:

Posted By Live Blog11:21 PM

Tuesday, January 13, 2015

[Tutorial] Ball - Basic Physics in cocos2d-x

Let's start

First, create a new project using cmd

>cocos new Ball -p com.vn.Ball -l cpp -d E:/android/project

Explain a bit, the above command will create a Project named Ball in folder E:/android/project

-p com.vn.Ball is the syntax of package. You can change a bit but must have 2 dots (.) like above. 
-l cpp: is the choice of C++
-d E:/android/project: is the folder that Project saved

Posted By Live Blog11:39 PM

[Tutorial] Hello cocos2d-x. The first code - Hello World!

Filled under:

A - Create and run Project

First, create a new project named HelloWorld using cmd

Run/cmd
>cocos new HelloWorld -p com.vn.HelloWorld -l cpp - d E:/android/myproject

Wait for 5 minutes to create new Project...

It's done. Go to new project in the following path
E:/android/myproject/helloworld
You can see the folder structure as follow:

Classes <- The most important, contains cpp or lua upon to your choice of language in above command.
cocos2d <- library of engine Cocos2d-x.
proj.android <- for building apk for Android mobile.
proj.ios_mac  <- for building apps for Iphone and Mac OS ( only run on Apple computers, or computer that installed Mac OS.
proj.linux <- for building apps on Linux machine.
proj.win32 <- for building apps on Windows 7, 8 OS
proj.wp8-xaml <- for building apps running on Windows Phone 8
Resources <- contains images, fonts, Maps, physics definition, etc.
.cocos-project.json <- for building project with lua or cpp.
CMakeLists.txt <- List libraries for building project.

Continue, we build and run on Windows. Using following command

>cocos run -s E:/android/myproject/helloworld -p win32

(enter cocos run -h for help)

>cocos compile -s E:/android/myproject/helloworld -p android --ap 16
--ap 16 is for android 4.1.2 or higher

Install on emulator
>adb install E:/android/myproject/helloworld/bin/debug/android/helloworld-debug-unligned.apk
or
>cocos run -s E:/android/myproject/helloworld -p android --ap 16

If error, remove --ap 16, as follow:
>cocos run -s E:/android/myproject/helloworld -p android

If not error and appear like this, it means you succeed. 


Posted By Live Blog6:49 PM

Monday, January 12, 2015

[Tutorial] How to setup Cocos2d - x V3.0 FINAL on Window OS step-by-step, 100% Working

Filled under:

Setup this Engine is really difficult to many one, because of not simple as running only file setup.exe, then Next, Next, finish. It requires system configuration, and setup auxiliaries for running. And running it also works through an editor program (like Visual Studio). 


Posted By Live Blog8:31 PM

Sunday, December 1, 2013

Enable design mode HTML page in Visual Studio 2013

By default, in VS version 2013 or later, we can't view html page in design mode as in older version VS. So, now we can enable design mode as following clip.

Posted By Live Blog7:33 PM

Tuesday, November 5, 2013

Make money $$$ for android dev with startapp

It's easy and simple! Now let's begin!

First, register a new account here: Register Start App


Choose I'm a developer



Posted By Live Blog11:15 AM

Sunday, October 6, 2013

Developping Android Apps is simple through simple Demo Apps - Part 22: Draw Shapes

Here's the tutorial how to draw shapes in android


[ttaiit.blogspot.com]

Posted By Live Blog3:56 AM

Thursday, October 3, 2013

Developping Android Apps is simple through simple Demo Apps - Part 21: Animate an image

Here's the tutorial how to animate an image


[ttaiit.blogspot.com]

Posted By Live Blog1:02 AM

Choose an Android item