SlideShare a Scribd company logo
Cocos2dx Realtime Fighting Game Tutorial
Since we released our Cocos2dx SDK, we’ve had a lot of positive feedback from developers. To make
things easier, we’ve also developed a demo real-time fighting game in Cocos2d-x to help developers
bootstrap easily. I’ll walk you through some of the key steps involved in doing this and the entire
source code can be downloaded or viewed from our git repo.
The demo game is quite simple – the user will first click on the “Start Game” button. Once started, the
scene changes to the game play scene. Since it’s a 2 player demo, another user will also do the same
from a different client and voila! they can shoot balls at each other by tapping on the screen and see
them move in real-time.
Now let’s understand how the game code works by examining the key code snippets. First we specify
the AppWarp constants that will be used in HelloWorldScene class
#define APPWARP_APP_KEY "Your App Key"
#define APPWARP_SECRET_KEY "Your Secret Key"
#define ROOM_ID "Your Room Id
You get your values by registering and creating an AppWarp type of application
from AppHQ (SheHertz AppWarp Dashboard). This wiki page contains a step-by-step guide on how
to register, creating the app and a game room. Once you’ve got these values, replace as indicated.
Also Read: Realtime Multiplayer Development on Cocos2d-x
Next we simply add the required UI elements (local player, remote player etc.). For the real-time
communication to happen, you need to include AppWarp Cocos2d-x in to your project. The latest
version including all the steps for setting up your xcode and Android projects can be downloaded from
our Cocos2DX Deveveloper Home. Add this source code to your project. Next you need to initialize
the AppWarp’s Client singleton and set up your listeners through which you will get events.
<
AppWarp::Client *warpClientRef;
AppWarp::Client::initialize(APPWARP_APP_KEY,APPWARP_SECRET_KEY);
warpClientRef = AppWarp::Client::getInstance();
warpClientRef->setConnectionRequestListener(this);
warpClientRef->setNotificationListener(this);
warpClientRef->setRoomRequestListener(this);
warpClientRef->setZoneRequestListener(this);
The listener callbacks required for this sample are defined in HelloWorldScene.cpp file, so
HelloWorldScene itself is added as a listener in the above code. ConnectionRequestListener defines
the callbacks for connection establishment and tear-down. RoomRequestListener defines the callbacks
for the game room’s join and subscribe operations. NotificationListener defines the callbacks for
remote notifications such a player sending a chat or updating a rooms properties etc.
class HelloWorld : public cocos2d::CCLayerColor, public
AppWarp::ConnectionRequestListener,
public AppWarp::RoomRequestListener,public
AppWarp::NotificationListener,public AppWarp::ZoneRequestListener
Now we are ready to connect to AppWarp cloud and start our game. Now each user who is concurrently
connected to your game must have a unique username. In this demo, we will use a simple random user
name generator function and use that as the username for connect. You can use other solutions such as
a facebook id, email address etc. to guarantee uniqueness depending on your game.
userName = genRandom();
warpClientRef->connect(userName);
The game starts once the user has successfully connected to AppWarp and joined (and subscribed) the
game room.The listener callbacks as a result of connect, joinRoom and subscribeRoom API calls are
defined as follows:
void HelloWorld::onConnectDone(int res)
{
if (res==0)
{
printf("nonConnectDone .. SUCCESSn");
AppWarp::Client *warpClientRef;
warpClientRef = AppWarp::Client::getInstance();
warpClientRef->joinRoom(ROOM_ID);
}
else
printf("nonConnectDone .. FAILEDn");
}
void HelloWorld::onJoinRoomDone(AppWarp::room revent)
{
if (revent.result==0)
{
printf("nonJoinRoomDone .. SUCCESSn");
AppWarp::Client *warpClientRef;
warpClientRef = AppWarp::Client::getInstance();
warpClientRef->subscribeRoom(ROOM_ID);
startGame();
removeStartGameLayer();
}
else
printf("nonJoinRoomDone .. FAILEDn");
}
void HelloWorld::onSubscribeRoomDone(AppWarp::room revent)
{
if (revent.result==0)
{
printf("nonSubscribeRoomDone .. SUCCESSn");
}
else
printf("nonSubscribeRoomDone .. FAILEDn");
}
The game starts when onJoinRoomDone event is fired with a success code. Now the user can shoot in
the opponents direction simply by tapping the screen in the direction he wants to shoot and that is
handled as follows:
void HelloWorld::ccTouchesEnded(cocos2d::CCSet *pTouches, cocos2d::CCEvent
*pEvent)
{
CCSetIterator it = pTouches->begin();
CCTouch* touch = (CCTouch*)(*it);
CCPoint location = touch->getLocation();
// Set up initial location of projectile
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCSprite *projectile = CCSprite::create("Bullet-red.png");
projectile->setPosition(ccp(player->getPosition().x+player-
>getContentSize().width/2,
player->getPosition().y));
CCPoint projectilePos = projectile->getPosition();
// Determine offset of location to projectile
int offX = location.x - projectilePos.x;
int offY = location.y - projectilePos.y;
// Bail out if we are shooting down or backwards
if (offX getContentSize().width/2);
float ratio = (float) offY / (float) offX;
int realY = (realX * ratio) + projectilePos.y;
CCPoint realDest = ccp(realX, realY);
// Determine the length of how far we're shooting
int offRealX = realX - projectilePos.x;
int offRealY = realY - projectilePos.y;
float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY));
float velocity = 480/1; // 480pixels/1sec
float realMoveDuration = length/velocity;
sendData(winSize.width-realDest.x, realDest.y, realMoveDuration);
// Move projectile to actual endpoint
CCActionInterval* move = CCMoveTo::create(realMoveDuration, realDest);
CCCallFuncN* moveFinished = CCCallFuncN::create(this,
callfuncN_selector(HelloWorld::spriteMoveFinished));
CCSequence* seq = CCSequence::create(move,moveFinished, NULL);
projectile->runAction(seq);
// Add to projectiles array
projectile->setTag(2);
_projectiles->addObject(projectile);
}
void HelloWorld::sendData(float x, float y, float duration)
{
AppWarp::Client *warpClientRef;
warpClientRef = AppWarp::Client::getInstance();
std::stringstream str;
str <sendChat(str.str()); }
Here we are sending x and y values of the touch point according to the remote player’s frame of
reference as well as the duration in which the projectile needs to go beyond the screen. The data is a
string where characters “x” and “d” are used as separators. This message is received by all players in
the room and they can then update their UI in turn (for drawing the projectile). When we receive remote
messages we need to write some code to update the remote player’s position or projectile depending
on the message received. Here is the code snippet which handles it in the HelloWorldScene.cpp file
void HelloWorld::onChatReceived(AppWarp::chat chatevent) { if(chatevent.sender
!= userName)
{ std::size_t loc = chatevent.chat.find('x'); std::string str1 =
chatevent.chat.substr(0,loc);
std::string str2 = chatevent.chat.substr(loc+1); loc =
chatevent.chat.find('d');
std::string str3 = chatevent.chat.substr(loc+1); float x = (float)std::atof
(str1.c_str());
float y = (float)std::atof(str2.c_str()); float dest =
(float)std::atof(str3.c_str());
updateEnemyStatus(ccp(x,y), dest); } } void
HelloWorld::updateEnemyStatus(CCPoint destination,
float actualDuration) { enemy->setOpacity(255);isEnemyAdded = true;
CCSprite *target = CCSprite::create("Bullet-blue.png");
target->setPosition(ccp(enemy->getPosition().x-enemy-
>getContentSize().width/2,
enemy->getPosition().y));
addChild(target,10);
// Move projectile to actual endpoint
CCActionInterval* move = CCMoveTo::create(actualDuration, destination);
CCCallFuncN* moveFinished = CCCallFuncN::create(this,
callfuncN_selector(HelloWorld::spriteMoveFinished));
CCSequence* seq = CCSequence::create(move,moveFinished, NULL);
target->runAction(seq);
// Add to targets array
target->setTag(3);
_targets->addObject(target);
}
That’s it! We saw how you can simply integrate the AppWarp library and add real-time communication
to your game. Get started with AppWarp to start developing rich and engaging real-time multiplayer
games in Cocos2DX. For questions and or feedback, send us a mail on support@shephertz.com

More Related Content

What's hot

Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations
DVClub
 
Side effects-con-redux
Side effects-con-reduxSide effects-con-redux
Side effects-con-redux
Nicolas Quiceno Benavides
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best Practices
Lluis Franco
 
The Ring programming language version 1.5.4 book - Part 82 of 185
The Ring programming language version 1.5.4 book - Part 82 of 185The Ring programming language version 1.5.4 book - Part 82 of 185
The Ring programming language version 1.5.4 book - Part 82 of 185
Mahmoud Samir Fayed
 
Hello, Is That FreeSWITCH? Then We're Coming to Check You!
Hello, Is That FreeSWITCH? Then We're Coming to Check You!Hello, Is That FreeSWITCH? Then We're Coming to Check You!
Hello, Is That FreeSWITCH? Then We're Coming to Check You!
PVS-Studio
 
The Ring programming language version 1.5.1 book - Part 78 of 180
The Ring programming language version 1.5.1 book - Part 78 of 180The Ring programming language version 1.5.1 book - Part 78 of 180
The Ring programming language version 1.5.1 book - Part 78 of 180
Mahmoud Samir Fayed
 
soscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profitsoscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profit
hanbeom Park
 
Arduino、Web 到 IoT
Arduino、Web 到 IoTArduino、Web 到 IoT
Arduino、Web 到 IoT
Justin Lin
 
Reanalyzing the Notepad++ project
Reanalyzing the Notepad++ projectReanalyzing the Notepad++ project
Reanalyzing the Notepad++ project
PVS-Studio
 
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft EdgeChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
PVS-Studio
 
The Ring programming language version 1.5.2 book - Part 74 of 181
The Ring programming language version 1.5.2 book - Part 74 of 181The Ring programming language version 1.5.2 book - Part 74 of 181
The Ring programming language version 1.5.2 book - Part 74 of 181
Mahmoud Samir Fayed
 
How to send gzipped requests with boto3
How to send gzipped requests with boto3How to send gzipped requests with boto3
How to send gzipped requests with boto3
Luciano Mammino
 
Intro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and BindingsIntro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and Bindings
Sergio Acosta
 

What's hot (13)

Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations
 
Side effects-con-redux
Side effects-con-reduxSide effects-con-redux
Side effects-con-redux
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best Practices
 
The Ring programming language version 1.5.4 book - Part 82 of 185
The Ring programming language version 1.5.4 book - Part 82 of 185The Ring programming language version 1.5.4 book - Part 82 of 185
The Ring programming language version 1.5.4 book - Part 82 of 185
 
Hello, Is That FreeSWITCH? Then We're Coming to Check You!
Hello, Is That FreeSWITCH? Then We're Coming to Check You!Hello, Is That FreeSWITCH? Then We're Coming to Check You!
Hello, Is That FreeSWITCH? Then We're Coming to Check You!
 
The Ring programming language version 1.5.1 book - Part 78 of 180
The Ring programming language version 1.5.1 book - Part 78 of 180The Ring programming language version 1.5.1 book - Part 78 of 180
The Ring programming language version 1.5.1 book - Part 78 of 180
 
soscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profitsoscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profit
 
Arduino、Web 到 IoT
Arduino、Web 到 IoTArduino、Web 到 IoT
Arduino、Web 到 IoT
 
Reanalyzing the Notepad++ project
Reanalyzing the Notepad++ projectReanalyzing the Notepad++ project
Reanalyzing the Notepad++ project
 
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft EdgeChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
 
The Ring programming language version 1.5.2 book - Part 74 of 181
The Ring programming language version 1.5.2 book - Part 74 of 181The Ring programming language version 1.5.2 book - Part 74 of 181
The Ring programming language version 1.5.2 book - Part 74 of 181
 
How to send gzipped requests with boto3
How to send gzipped requests with boto3How to send gzipped requests with boto3
How to send gzipped requests with boto3
 
Intro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and BindingsIntro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and Bindings
 

Similar to A Complete Tutorial to Develop Real-Time Fighting Game with Cocos2dx

Shape12 6
Shape12 6Shape12 6
Shape12 6
pslulli
 
Android game development
Android game developmentAndroid game development
Android game development
dmontagni
 
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ -  Automated Malware AnalysisIstSec'14 - İbrahim BALİÇ -  Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
BGA Cyber Security
 
Sony C#/.NET component set analysis
Sony C#/.NET component set analysisSony C#/.NET component set analysis
Sony C#/.NET component set analysis
PVS-Studio
 
viWave Study Group - Introduction to Google Android Development - Chapter 23 ...
viWave Study Group - Introduction to Google Android Development - Chapter 23 ...viWave Study Group - Introduction to Google Android Development - Chapter 23 ...
viWave Study Group - Introduction to Google Android Development - Chapter 23 ...
Ted Chien
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.io
Katy Slemon
 
The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184
Mahmoud Samir Fayed
 
WebRTC 101 - How to get started building your first WebRTC application
WebRTC 101 - How to get started building your first WebRTC applicationWebRTC 101 - How to get started building your first WebRTC application
WebRTC 101 - How to get started building your first WebRTC application
Dan Jenkins
 
Criando jogos para o windows 8
Criando jogos para o windows 8Criando jogos para o windows 8
Criando jogos para o windows 8
José Farias
 
The Ring programming language version 1.7 book - Part 87 of 196
The Ring programming language version 1.7 book - Part 87 of 196The Ring programming language version 1.7 book - Part 87 of 196
The Ring programming language version 1.7 book - Part 87 of 196
Mahmoud Samir Fayed
 
Build on Streakk Chain - Blockchain
Build on Streakk Chain - BlockchainBuild on Streakk Chain - Blockchain
Build on Streakk Chain - Blockchain
Earn.World
 
Automated malware analysis
Automated malware analysisAutomated malware analysis
Automated malware analysis
Ibrahim Baliç
 
SSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and SchedulingSSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and Scheduling
David Evans
 
R-House (LSRC)
R-House (LSRC)R-House (LSRC)
R-House (LSRC)
Fernand Galiana
 
Android RenderScript
Android RenderScriptAndroid RenderScript
Android RenderScript
Jungsoo Nam
 
Pandora FMS: Windows Phone 7 Agent
Pandora FMS: Windows Phone 7 AgentPandora FMS: Windows Phone 7 Agent
Pandora FMS: Windows Phone 7 Agent
Pandora FMS
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
Andrey Karpov
 
Book
BookBook
Book
luis_lmro
 
Virtual Network Computing Based Droid desktop
Virtual Network Computing Based Droid desktopVirtual Network Computing Based Droid desktop
Virtual Network Computing Based Droid desktop
IOSR Journals
 
Multiplayer Networking Game
Multiplayer Networking GameMultiplayer Networking Game
Multiplayer Networking Game
Tanmay Krishna
 

Similar to A Complete Tutorial to Develop Real-Time Fighting Game with Cocos2dx (20)

Shape12 6
Shape12 6Shape12 6
Shape12 6
 
Android game development
Android game developmentAndroid game development
Android game development
 
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ -  Automated Malware AnalysisIstSec'14 - İbrahim BALİÇ -  Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
 
Sony C#/.NET component set analysis
Sony C#/.NET component set analysisSony C#/.NET component set analysis
Sony C#/.NET component set analysis
 
viWave Study Group - Introduction to Google Android Development - Chapter 23 ...
viWave Study Group - Introduction to Google Android Development - Chapter 23 ...viWave Study Group - Introduction to Google Android Development - Chapter 23 ...
viWave Study Group - Introduction to Google Android Development - Chapter 23 ...
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.io
 
The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184
 
WebRTC 101 - How to get started building your first WebRTC application
WebRTC 101 - How to get started building your first WebRTC applicationWebRTC 101 - How to get started building your first WebRTC application
WebRTC 101 - How to get started building your first WebRTC application
 
Criando jogos para o windows 8
Criando jogos para o windows 8Criando jogos para o windows 8
Criando jogos para o windows 8
 
The Ring programming language version 1.7 book - Part 87 of 196
The Ring programming language version 1.7 book - Part 87 of 196The Ring programming language version 1.7 book - Part 87 of 196
The Ring programming language version 1.7 book - Part 87 of 196
 
Build on Streakk Chain - Blockchain
Build on Streakk Chain - BlockchainBuild on Streakk Chain - Blockchain
Build on Streakk Chain - Blockchain
 
Automated malware analysis
Automated malware analysisAutomated malware analysis
Automated malware analysis
 
SSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and SchedulingSSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and Scheduling
 
R-House (LSRC)
R-House (LSRC)R-House (LSRC)
R-House (LSRC)
 
Android RenderScript
Android RenderScriptAndroid RenderScript
Android RenderScript
 
Pandora FMS: Windows Phone 7 Agent
Pandora FMS: Windows Phone 7 AgentPandora FMS: Windows Phone 7 Agent
Pandora FMS: Windows Phone 7 Agent
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
 
Book
BookBook
Book
 
Virtual Network Computing Based Droid desktop
Virtual Network Computing Based Droid desktopVirtual Network Computing Based Droid desktop
Virtual Network Computing Based Droid desktop
 
Multiplayer Networking Game
Multiplayer Networking GameMultiplayer Networking Game
Multiplayer Networking Game
 

More from ShepHertz

ShepHertz Facial recognition based attendance and visitor management system
ShepHertz Facial recognition based attendance and visitor management systemShepHertz Facial recognition based attendance and visitor management system
ShepHertz Facial recognition based attendance and visitor management system
ShepHertz
 
Configure &amp; send push notification on i os device
Configure &amp; send push notification on i os deviceConfigure &amp; send push notification on i os device
Configure &amp; send push notification on i os device
ShepHertz
 
Complete steps to Integrate Push Notification for Your Cocos2dx App with Push...
Complete steps to Integrate Push Notification for Your Cocos2dx App with Push...Complete steps to Integrate Push Notification for Your Cocos2dx App with Push...
Complete steps to Integrate Push Notification for Your Cocos2dx App with Push...
ShepHertz
 
Media &amp; entertainment marketing automation and omnichannel media
Media &amp; entertainment marketing automation and omnichannel mediaMedia &amp; entertainment marketing automation and omnichannel media
Media &amp; entertainment marketing automation and omnichannel media
ShepHertz
 
Insurance marketing automation and omni channel insurance.
Insurance marketing automation and omni channel insurance.Insurance marketing automation and omni channel insurance.
Insurance marketing automation and omni channel insurance.
ShepHertz
 
Travel and aviation marketing automation and omnichannel travel
Travel and aviation marketing automation and omnichannel travelTravel and aviation marketing automation and omnichannel travel
Travel and aviation marketing automation and omnichannel travel
ShepHertz
 
Gaming marketing automation and multiplayer game development
Gaming marketing automation and multiplayer game developmentGaming marketing automation and multiplayer game development
Gaming marketing automation and multiplayer game development
ShepHertz
 
Retail marketing automation and omni channel retail experience.
Retail marketing automation and omni channel retail experience.Retail marketing automation and omni channel retail experience.
Retail marketing automation and omni channel retail experience.
ShepHertz
 
Banking Services Marketing Automation and Omni-channel Banking
Banking Services Marketing Automation and Omni-channel BankingBanking Services Marketing Automation and Omni-channel Banking
Banking Services Marketing Automation and Omni-channel Banking
ShepHertz
 
ShepHertz Cloud Ecosystem for Apps
ShepHertz Cloud Ecosystem for AppsShepHertz Cloud Ecosystem for Apps
ShepHertz Cloud Ecosystem for Apps
ShepHertz
 
Push Notification with Unity in iOS using App42 Backend
Push Notification with Unity in iOS using App42 BackendPush Notification with Unity in iOS using App42 Backend
Push Notification with Unity in iOS using App42 Backend
ShepHertz
 
ShepHertz - アプリのための万全なエコシステム
ShepHertz - アプリのための万全なエコシステムShepHertz - アプリのための万全なエコシステム
ShepHertz - アプリのための万全なエコシステム
ShepHertz
 
Configuring MongoDB HA Replica Set on AWS EC2
Configuring MongoDB HA Replica Set on AWS EC2Configuring MongoDB HA Replica Set on AWS EC2
Configuring MongoDB HA Replica Set on AWS EC2
ShepHertz
 
App42 Student Lab - Android Game Dev Series V 0.1
App42 Student Lab - Android Game Dev Series V 0.1App42 Student Lab - Android Game Dev Series V 0.1
App42 Student Lab - Android Game Dev Series V 0.1
ShepHertz
 
ShepHertz - A Complete Cloud Ecosystem for your Apps
ShepHertz - A Complete Cloud Ecosystem for your AppsShepHertz - A Complete Cloud Ecosystem for your Apps
ShepHertz - A Complete Cloud Ecosystem for your Apps
ShepHertz
 

More from ShepHertz (15)

ShepHertz Facial recognition based attendance and visitor management system
ShepHertz Facial recognition based attendance and visitor management systemShepHertz Facial recognition based attendance and visitor management system
ShepHertz Facial recognition based attendance and visitor management system
 
Configure &amp; send push notification on i os device
Configure &amp; send push notification on i os deviceConfigure &amp; send push notification on i os device
Configure &amp; send push notification on i os device
 
Complete steps to Integrate Push Notification for Your Cocos2dx App with Push...
Complete steps to Integrate Push Notification for Your Cocos2dx App with Push...Complete steps to Integrate Push Notification for Your Cocos2dx App with Push...
Complete steps to Integrate Push Notification for Your Cocos2dx App with Push...
 
Media &amp; entertainment marketing automation and omnichannel media
Media &amp; entertainment marketing automation and omnichannel mediaMedia &amp; entertainment marketing automation and omnichannel media
Media &amp; entertainment marketing automation and omnichannel media
 
Insurance marketing automation and omni channel insurance.
Insurance marketing automation and omni channel insurance.Insurance marketing automation and omni channel insurance.
Insurance marketing automation and omni channel insurance.
 
Travel and aviation marketing automation and omnichannel travel
Travel and aviation marketing automation and omnichannel travelTravel and aviation marketing automation and omnichannel travel
Travel and aviation marketing automation and omnichannel travel
 
Gaming marketing automation and multiplayer game development
Gaming marketing automation and multiplayer game developmentGaming marketing automation and multiplayer game development
Gaming marketing automation and multiplayer game development
 
Retail marketing automation and omni channel retail experience.
Retail marketing automation and omni channel retail experience.Retail marketing automation and omni channel retail experience.
Retail marketing automation and omni channel retail experience.
 
Banking Services Marketing Automation and Omni-channel Banking
Banking Services Marketing Automation and Omni-channel BankingBanking Services Marketing Automation and Omni-channel Banking
Banking Services Marketing Automation and Omni-channel Banking
 
ShepHertz Cloud Ecosystem for Apps
ShepHertz Cloud Ecosystem for AppsShepHertz Cloud Ecosystem for Apps
ShepHertz Cloud Ecosystem for Apps
 
Push Notification with Unity in iOS using App42 Backend
Push Notification with Unity in iOS using App42 BackendPush Notification with Unity in iOS using App42 Backend
Push Notification with Unity in iOS using App42 Backend
 
ShepHertz - アプリのための万全なエコシステム
ShepHertz - アプリのための万全なエコシステムShepHertz - アプリのための万全なエコシステム
ShepHertz - アプリのための万全なエコシステム
 
Configuring MongoDB HA Replica Set on AWS EC2
Configuring MongoDB HA Replica Set on AWS EC2Configuring MongoDB HA Replica Set on AWS EC2
Configuring MongoDB HA Replica Set on AWS EC2
 
App42 Student Lab - Android Game Dev Series V 0.1
App42 Student Lab - Android Game Dev Series V 0.1App42 Student Lab - Android Game Dev Series V 0.1
App42 Student Lab - Android Game Dev Series V 0.1
 
ShepHertz - A Complete Cloud Ecosystem for your Apps
ShepHertz - A Complete Cloud Ecosystem for your AppsShepHertz - A Complete Cloud Ecosystem for your Apps
ShepHertz - A Complete Cloud Ecosystem for your Apps
 

Recently uploaded

AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
Ajin Abraham
 
From Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMsFrom Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMs
Sease
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024
Vadym Kazulkin
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
Fwdays
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
What is an RPA CoE? Session 2 – CoE Roles
What is an RPA CoE?  Session 2 – CoE RolesWhat is an RPA CoE?  Session 2 – CoE Roles
What is an RPA CoE? Session 2 – CoE Roles
DianaGray10
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
Fwdays
 
Demystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through StorytellingDemystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through Storytelling
Enterprise Knowledge
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Pitangent Analytics & Technology Solutions Pvt. Ltd
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 

Recently uploaded (20)

AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
 
From Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMsFrom Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMs
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
What is an RPA CoE? Session 2 – CoE Roles
What is an RPA CoE?  Session 2 – CoE RolesWhat is an RPA CoE?  Session 2 – CoE Roles
What is an RPA CoE? Session 2 – CoE Roles
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
 
Demystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through StorytellingDemystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through Storytelling
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 

A Complete Tutorial to Develop Real-Time Fighting Game with Cocos2dx

  • 1. Cocos2dx Realtime Fighting Game Tutorial Since we released our Cocos2dx SDK, we’ve had a lot of positive feedback from developers. To make things easier, we’ve also developed a demo real-time fighting game in Cocos2d-x to help developers bootstrap easily. I’ll walk you through some of the key steps involved in doing this and the entire source code can be downloaded or viewed from our git repo. The demo game is quite simple – the user will first click on the “Start Game” button. Once started, the scene changes to the game play scene. Since it’s a 2 player demo, another user will also do the same from a different client and voila! they can shoot balls at each other by tapping on the screen and see them move in real-time.
  • 2. Now let’s understand how the game code works by examining the key code snippets. First we specify the AppWarp constants that will be used in HelloWorldScene class #define APPWARP_APP_KEY "Your App Key" #define APPWARP_SECRET_KEY "Your Secret Key" #define ROOM_ID "Your Room Id You get your values by registering and creating an AppWarp type of application from AppHQ (SheHertz AppWarp Dashboard). This wiki page contains a step-by-step guide on how to register, creating the app and a game room. Once you’ve got these values, replace as indicated. Also Read: Realtime Multiplayer Development on Cocos2d-x Next we simply add the required UI elements (local player, remote player etc.). For the real-time communication to happen, you need to include AppWarp Cocos2d-x in to your project. The latest version including all the steps for setting up your xcode and Android projects can be downloaded from our Cocos2DX Deveveloper Home. Add this source code to your project. Next you need to initialize the AppWarp’s Client singleton and set up your listeners through which you will get events. < AppWarp::Client *warpClientRef; AppWarp::Client::initialize(APPWARP_APP_KEY,APPWARP_SECRET_KEY); warpClientRef = AppWarp::Client::getInstance(); warpClientRef->setConnectionRequestListener(this); warpClientRef->setNotificationListener(this); warpClientRef->setRoomRequestListener(this); warpClientRef->setZoneRequestListener(this); The listener callbacks required for this sample are defined in HelloWorldScene.cpp file, so HelloWorldScene itself is added as a listener in the above code. ConnectionRequestListener defines
  • 3. the callbacks for connection establishment and tear-down. RoomRequestListener defines the callbacks for the game room’s join and subscribe operations. NotificationListener defines the callbacks for remote notifications such a player sending a chat or updating a rooms properties etc. class HelloWorld : public cocos2d::CCLayerColor, public AppWarp::ConnectionRequestListener, public AppWarp::RoomRequestListener,public AppWarp::NotificationListener,public AppWarp::ZoneRequestListener Now we are ready to connect to AppWarp cloud and start our game. Now each user who is concurrently connected to your game must have a unique username. In this demo, we will use a simple random user name generator function and use that as the username for connect. You can use other solutions such as a facebook id, email address etc. to guarantee uniqueness depending on your game. userName = genRandom(); warpClientRef->connect(userName); The game starts once the user has successfully connected to AppWarp and joined (and subscribed) the game room.The listener callbacks as a result of connect, joinRoom and subscribeRoom API calls are defined as follows: void HelloWorld::onConnectDone(int res) { if (res==0) { printf("nonConnectDone .. SUCCESSn"); AppWarp::Client *warpClientRef; warpClientRef = AppWarp::Client::getInstance(); warpClientRef->joinRoom(ROOM_ID); } else printf("nonConnectDone .. FAILEDn"); } void HelloWorld::onJoinRoomDone(AppWarp::room revent) { if (revent.result==0) { printf("nonJoinRoomDone .. SUCCESSn"); AppWarp::Client *warpClientRef; warpClientRef = AppWarp::Client::getInstance(); warpClientRef->subscribeRoom(ROOM_ID); startGame(); removeStartGameLayer();
  • 4. } else printf("nonJoinRoomDone .. FAILEDn"); } void HelloWorld::onSubscribeRoomDone(AppWarp::room revent) { if (revent.result==0) { printf("nonSubscribeRoomDone .. SUCCESSn"); } else printf("nonSubscribeRoomDone .. FAILEDn"); } The game starts when onJoinRoomDone event is fired with a success code. Now the user can shoot in the opponents direction simply by tapping the screen in the direction he wants to shoot and that is handled as follows: void HelloWorld::ccTouchesEnded(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent) { CCSetIterator it = pTouches->begin(); CCTouch* touch = (CCTouch*)(*it); CCPoint location = touch->getLocation(); // Set up initial location of projectile CCSize winSize = CCDirector::sharedDirector()->getWinSize(); CCSprite *projectile = CCSprite::create("Bullet-red.png"); projectile->setPosition(ccp(player->getPosition().x+player- >getContentSize().width/2, player->getPosition().y)); CCPoint projectilePos = projectile->getPosition(); // Determine offset of location to projectile int offX = location.x - projectilePos.x; int offY = location.y - projectilePos.y; // Bail out if we are shooting down or backwards if (offX getContentSize().width/2); float ratio = (float) offY / (float) offX; int realY = (realX * ratio) + projectilePos.y; CCPoint realDest = ccp(realX, realY); // Determine the length of how far we're shooting int offRealX = realX - projectilePos.x; int offRealY = realY - projectilePos.y; float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY)); float velocity = 480/1; // 480pixels/1sec float realMoveDuration = length/velocity;
  • 5. sendData(winSize.width-realDest.x, realDest.y, realMoveDuration); // Move projectile to actual endpoint CCActionInterval* move = CCMoveTo::create(realMoveDuration, realDest); CCCallFuncN* moveFinished = CCCallFuncN::create(this, callfuncN_selector(HelloWorld::spriteMoveFinished)); CCSequence* seq = CCSequence::create(move,moveFinished, NULL); projectile->runAction(seq); // Add to projectiles array projectile->setTag(2); _projectiles->addObject(projectile); } void HelloWorld::sendData(float x, float y, float duration) { AppWarp::Client *warpClientRef; warpClientRef = AppWarp::Client::getInstance(); std::stringstream str; str <sendChat(str.str()); } Here we are sending x and y values of the touch point according to the remote player’s frame of reference as well as the duration in which the projectile needs to go beyond the screen. The data is a string where characters “x” and “d” are used as separators. This message is received by all players in the room and they can then update their UI in turn (for drawing the projectile). When we receive remote messages we need to write some code to update the remote player’s position or projectile depending on the message received. Here is the code snippet which handles it in the HelloWorldScene.cpp file void HelloWorld::onChatReceived(AppWarp::chat chatevent) { if(chatevent.sender != userName) { std::size_t loc = chatevent.chat.find('x'); std::string str1 = chatevent.chat.substr(0,loc); std::string str2 = chatevent.chat.substr(loc+1); loc = chatevent.chat.find('d'); std::string str3 = chatevent.chat.substr(loc+1); float x = (float)std::atof (str1.c_str()); float y = (float)std::atof(str2.c_str()); float dest = (float)std::atof(str3.c_str()); updateEnemyStatus(ccp(x,y), dest); } } void HelloWorld::updateEnemyStatus(CCPoint destination, float actualDuration) { enemy->setOpacity(255);isEnemyAdded = true; CCSprite *target = CCSprite::create("Bullet-blue.png"); target->setPosition(ccp(enemy->getPosition().x-enemy- >getContentSize().width/2, enemy->getPosition().y)); addChild(target,10); // Move projectile to actual endpoint CCActionInterval* move = CCMoveTo::create(actualDuration, destination); CCCallFuncN* moveFinished = CCCallFuncN::create(this, callfuncN_selector(HelloWorld::spriteMoveFinished));
  • 6. CCSequence* seq = CCSequence::create(move,moveFinished, NULL); target->runAction(seq); // Add to targets array target->setTag(3); _targets->addObject(target); } That’s it! We saw how you can simply integrate the AppWarp library and add real-time communication to your game. Get started with AppWarp to start developing rich and engaging real-time multiplayer games in Cocos2DX. For questions and or feedback, send us a mail on support@shephertz.com