RandomDungeon

 

Its still a work in progress procedural dungeon using BSP!!! Check out the next post for a game out of this!!

Created this Script for procedural dungeon generation, but wasn’t useful since separating rooms using this technique creates lot of issues while creating path between rooms. But hopefully this will help some one who wants to avoid overlapping rects.

 bool SteerSeparation()  
 {  
      bool noOverlap = true;  
      //_packs is a list of pack(object which contains rect object)
      // all the rects are at same position (0, 0)
      foreach (var pack in _packs)  
      {  
           foreach (var item in _packs)  
           {  
                if (pack.GetHashCode() != item.GetHashCode())  
                {  
                     while (pack.rect.Overlaps(item.rect))  
                     {  
                          Rect rect1 = pack.rect;  
                          Rect rect2 = item.rect;  
                          //create a geometric center between two rects
                          Rect geometricCenter = GetGeometricCenter(rect1, rect2);  
                          pack.rect = Steer(rect1, geometricCenter);  
                          item.rect = Steer(rect2, geometricCenter);  
                          noOverlap = false;  
                     }  
                }  
           }  
      }  
      return noOverlap;  
 }  
 Rect Steer(Rect rect, Rect geometricCenter)  
 {  
      Vector2 dir = new Vector2(rect.center.x - geometricCenter.center.x, rect.center.y - geometricCenter.center.y);  
      rect.center += dir * Time.deltaTime * 0.1f;  
      return rect;  
 }  
 private Rect GetGeometricCenter(Rect rect1, Rect rect2)  
 {  
      Rect rect = new Rect();  
      rect.x = Mathf.Min(rect1.x, rect2.x);  
      rect.y = Mathf.Min(rect1.y, rect2.y);  
      //calculate width  
      if (rect1.x < rect2.x)  
      {  
           if (rect2.x + rect2.width < rect1.x + rect1.width)  
           {  
                rect.width = rect1.width;  
           }  
           else  
           {  
                rect.width = rect1.x + rect1.width - rect2.x;  
           }  
      }  
      else if (rect1.x > rect2.x)  
      {  
           if (rect1.x + rect1.width < rect2.x + rect2.width)  
           {  
                rect.width = rect2.width;  
           }  
           else  
           {  
                rect.width = rect2.x + rect2.width - rect1.x;  
           }  
      }  
      else  
      {  
           rect.width = Mathf.Max(rect1.width, rect2.width);  
      }  
      //calculate height  
      if (rect1.y < rect2.y)  
      {  
           if (rect2.y + rect2.height < rect1.y + rect1.height)  
           {  
                rect.height = rect1.height;  
           }  
           else  
           {  
                rect.height = rect1.y + rect1.height - rect2.y;  
           }  
      }  
      else if (rect1.y > rect2.y)  
      {  
           if (rect1.y + rect1.height < rect2.y + rect2.height)  
           {  
                rect.height = rect2.height;  
           }  
           else  
           {  
                rect.height = rect2.y + rect2.height - rect1.y;  
           }  
      }  
      else  
      {  
           rect.height = Mathf.Max(rect1.height, rect2.height);  
      }  
      return rect;  
 }  

happy coding 🙂

Attach the below Script to an empty game object, and then apply the shader below to the material. I have created a plane from scratch for this to work as desired and easy to customize. The script that creates plane is also posted here.

The code is not explained in detail, if you have any difficulties please comment….

 using UnityEngine;  
 [RequireComponent (typeof(MeshFilter), typeof(MeshRenderer))]  
 public class FogOfWar : MonoBehaviour   
 {  
   Transform _player;  
   CustomPlane _plane;  
   Mesh _mesh;  
   public int explorerRangeX;  
   public int explorerRangeY;  
   TVec2<int> _lastExploredIndex;  
   void Awake()  
   {  
     _player = GameObject.FindGameObjectWithTag("Player").transform;  
     _mesh = GetComponent<MeshFilter>().mesh;  
     _mesh.Clear();  
     Events.instance.AddListener<GameEvent>(GenerateFogOfWar);  
   }  
   void GenerateFogOfWar(GameEvent e)  
   {  
     if (e.type == GameEvent.GENERATE_FOW)  
     {  
       Events.instance.RemoveListener<GameEvent>(GenerateFogOfWar);  
       _plane = new CustomPlane(e.width * e.gridSize, e.height * e.gridSize, (e.width * 8 / 512));  
       _mesh.vertices = _plane.getVertices();  
       _mesh.triangles = _plane.getTriangles();  
       _mesh.uv = _plane.getUVs();  
       _mesh.colors32 = _plane.getColors();  
       gameObject.transform.Translate(new Vector3(-_plane.width / 2, 0, -_plane.height / 2));  
       MeshCollider collider = gameObject.AddComponent<MeshCollider>();  
       collider.sharedMesh = _mesh;  
       _lastExploredIndex = new TVec2<int>(-1, -1);  
     }  
   }  
   void OnRenderObject()  
   {  
     Ray ray = new Ray(_player.position + Vector3.up * 20.0f, Vector3.down);  
     RaycastHit hitInfo;  
     if (Physics.Raycast(ray, out hitInfo, 5.0f))  
     {  
       Explore(gameObject.transform.InverseTransformPoint(hitInfo.point));  
     }  
   }  
   void UpdatePolygonColorAtIndex(int indexX, int indexY, int rangeX, int rangeY, byte alpha, bool isBorder = false)  
   {  
     for (int x = -rangeX; x <= rangeX; x++)  
     {  
       for (int y = -rangeY; y <= rangeY; y++)  
       {  
         if (isBorder)  
         {  
           if (x != -rangeX && x != rangeX && y != -rangeY && y != rangeY)  
           {  
             continue;  
           }  
         }  
         if (  
           _plane.isWithinRange((indexX + x), (indexY + y)) &&  
           _plane[indexX+x, indexY+y].getAlpha() > alpha)  
         {  
           _plane.UpdatePolygonColorAtIndex(indexX + x, indexY + y, new Color32(0, 0, 0, alpha));  
         }  
       }  
     }  
   }  
   void Explore(Vector3 position)  
   {  
     Vector2 quadIndex = _plane.GetPolygonIndexFromPosition(position);  
     int indexX = (int)quadIndex.x;  
     int indexY = (int)quadIndex.y;  
     if (_lastExploredIndex.x == indexX && _lastExploredIndex.y == indexY)  
     {  
       //don't update  
     }  
     else  
     {  
       UpdatePolygonColorAtIndex(indexX, indexY, explorerRangeX + 1, explorerRangeY + 1, 64, true);  
       UpdatePolygonColorAtIndex(indexX, indexY, explorerRangeX, explorerRangeY, 0, false);  
       UpdatePolygonColorAtIndex(indexX, indexY, explorerRangeX + 3, explorerRangeY, 64, true);  
       UpdatePolygonColorAtIndex(indexX, indexY, explorerRangeX + 2, explorerRangeY - 1, 0, false);  
       UpdatePolygonColorAtIndex(indexX, indexY, explorerRangeX, explorerRangeY + 2, 64, true);  
       UpdatePolygonColorAtIndex(indexX, indexY, explorerRangeX - 1, explorerRangeY + 1, 0, false);  
       _mesh.colors32 = _plane.getColors();  
       _lastExploredIndex.Set(indexX, indexY);  
     }  
   }  
 }  

Shader Code
:

 Shader "Custom/VertexAlphaFow"  
 {  
      Properties  
      {  
           _Color("Color", Color) = (1,1,1,1)  
           _MainTex("Base Albedo (RGB)", 2D) = "white" {}  
      }  
      SubShader  
      {  
           Tags{ "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" }  
           Blend SrcAlpha OneMinusSrcAlpha  
           pass  
           {  
                CGPROGRAM  
                #pragma fragmentoption ARB_precision_hint_fastest  
                #pragma vertex vert  
                #pragma fragment frag  
                #include "UnityCG.cginc"  
                #pragma target 3.0  
                uniform sampler2D _MainTex;  
                struct Vertex  
                {  
                     float4 vertex : POSITION;  
                     float4 color : COLOR;  
                     float4 texCoord : TEXCOORD0;  
                };  
                struct Fragment  
                {  
                     float4 pos : SV_POSITION;  
                     half4 color : COLOR;  
                     half2 uv : TEXCOORD0;  
                };  
                Fragment vert(Vertex i)  
                {  
                     Fragment fragOut;  
                     fragOut.color = i.color;  
                     fragOut.pos = mul(UNITY_MATRIX_MVP, i.vertex);  
                     fragOut.uv = i.texCoord;  
                     return fragOut;  
                }  
                half4 frag(Fragment i) : COLOR  
                {  
                     //in case want a tex  
                     //return half4(tex2D(_MainTex, i.uv).rgb, i.color.a);  
                     //use vertex color  
                     return i.color;  
                }  
                ENDCG  
           }  
      }  
           FallBack "VertexLit"  
 }  

Custom Plane Script

 using UnityEngine;  
 using System.Collections.Generic;  
 public class CustomPlane  
 {  
   private Polygon[,] _polygons;  
   public Polygon this[int x, int y]  
   {  
     get  
     {  
       return _polygons[x, y];  
     }  
   }  
   private int _quadSize;  
   public int quadSize  
   {  
     get  
     {  
       return _quadSize;  
     }  
     set  
     {  
       _quadSize = value;  
     }  
   }  
   private int _width;  
   public int width  
   {  
     get  
     {  
       return _width;  
     }  
     set  
     {  
       _width = value;  
     }  
   }  
   private int _height;  
   public int height  
   {  
     get  
     {  
       return _height;  
     }  
     set  
     {  
       _height = value;  
     }  
   }  
   private List<Vector3> _vertices;  
   private List<Vector2> _uvs;  
   private List<int> _triangles;  
   private List<Color32> _colors;  
   public CustomPlane(int width, int height, int quadSize)  
   {  
     _quadSize = quadSize;  
     _width = width;  
     _height = height;  
     _vertices = new List<Vector3>();  
     _triangles = new List<int>();  
     _uvs = new List<Vector2>();  
     _colors = new List<Color32>();  
     int row = Mathf.CeilToInt(_width / _quadSize);  
     int col = Mathf.CeilToInt(_height / _quadSize);  
     _polygons = new Polygon[row, col];  
     int runningIndex = -1;  
     for (int x = 0; x < row; x++)  
     {  
       for (int y = 0; y < col; y++)  
       {  
         int lastRunningIndex = runningIndex;  
         Vertex bottomLeft = (x - 1 > -1) ? _polygons[x - 1, y].bottomRight : (y - 1 > -1) ? _polygons[x, y - 1].topLeft : Polygon.getNode("bl", x, y, quadSize, ++runningIndex);  
         if (lastRunningIndex != runningIndex)  
         {  
           _vertices.Add(bottomLeft.position);  
         }  
         lastRunningIndex = runningIndex;  
         Vertex topLeft = (x - 1 > -1) ? _polygons[x - 1, y].topRight : Polygon.getNode("tl", x, y, quadSize, ++runningIndex);  
         if (lastRunningIndex != runningIndex)  
         {  
           _vertices.Add(topLeft.position);  
         }  
         lastRunningIndex = runningIndex;  
         Vertex topRight = Polygon.getNode("tr", x, y, quadSize, ++runningIndex);  
         if (lastRunningIndex != runningIndex)  
         {  
           _vertices.Add(topRight.position);  
         }  
         lastRunningIndex = runningIndex;  
         Vertex bottomRight = (y - 1 > -1) ? _polygons[x, y - 1].topRight : Polygon.getNode("br", x, y, quadSize, ++runningIndex);  
         if (lastRunningIndex != runningIndex)  
         {  
           _vertices.Add(bottomRight.position);  
         }  
         _polygons[x, y] = new Polygon(bottomLeft, topLeft, topRight, bottomRight, new Color32(0, 0, 0, 255));  
         _triangles.Add(bottomLeft.index);  
         _triangles.Add(topLeft.index);  
         _triangles.Add(topRight.index);  
         _triangles.Add(bottomRight.index);  
         _triangles.Add(bottomLeft.index);  
         _triangles.Add(topRight.index);  
       }  
     }  
     //generate uv's & color  
     int length = _vertices.Count;  
     for (int index = 0; index < length; index++)  
     {  
       _uvs.Add(  
             new Vector2(  
                 Mathf.InverseLerp(0, _width, _vertices[index].x),  
                 Mathf.InverseLerp(0, _height, _vertices[index].z)  
               )  
         );  
       _colors.Add(new Color32(0, 0, 0, 128));  
     }  
   }  
   public Vector3[] getVertices()  
   {  
     return _vertices.ToArray();  
   }  
   public int[] getTriangles()  
   {  
     return _triangles.ToArray();  
   }  
   public Vector2[] getUVs()  
   {  
     return _uvs.ToArray();  
   }  
   public Color32[] getColors()  
   {  
     return _colors.ToArray();  
   }  
   public Vector2 GetPolygonIndexFromTexCoord(Vector2 texCoord)  
   {  
     int xIndex, yIndex = 0;  
     xIndex = Mathf.CeilToInt((texCoord.x * _width) / _quadSize);  
     yIndex = Mathf.CeilToInt((texCoord.y * _height) / _quadSize);  
     return new Vector2(xIndex, yIndex);  
   }  
   public Vector2 GetPolygonIndexFromPosition(Vector3 position)  
   {  
     int xIndex, yIndex = 0;  
     xIndex = Mathf.FloorToInt(position.x / _quadSize);  
     yIndex = Mathf.FloorToInt(position.z / _quadSize);  
     return new Vector2(xIndex, yIndex);  
   }  
   private void UpdateColorAt(int vertexIndex, Color32 color)  
   {  
     _colors[vertexIndex] = color;  
   }  
   public bool isWithinRange(int x, int y)  
   {  
     return ((x >= 0 && x < _polygons.GetLength(0)) && (y >= 0 && y < _polygons.GetLength(1)));  
   }  
   public void UpdatePolygonColorAtIndex(int x, int y, Color32 color)  
   {  
     Polygon poly = _polygons[x, y];  
     //update polygon data  
     poly.UpdateColor(color);  
     //update render data from updated polygon  
     UpdateColorAt(poly.bottomLeft.index, color);  
     UpdateColorAt(poly.topLeft.index, color);  
     UpdateColorAt(poly.topRight.index, color);  
     UpdateColorAt(poly.bottomRight.index, color);  
   }  
 }  

Happy Coding 🙂

 using UnityEngine;  
 using System.Collections;  
 using System.Collections.Generic;  
 public class TrajectoryScript : MonoBehaviour   
 {  
      List<GameObject> _trajectoryPoints;  
      private bool _canDraw;  
      public static float theta;  
      public int _numOfPoints;  
      public static float distance;  
      public bool CanDraw  
      {  
           get  
           {  
                return _canDraw;  
           }  
           set  
           {  
                _canDraw = value;  
           }  
      }  
      void Start ()   
      {  
           _trajectoryPoints = new List<GameObject>();  
           for (int index = 0; index < _numOfPoints; index++)  
           {  
                GameObject point = (GameObject)Instantiate(Resources.Load("prefabs/trajectory"));  
                _trajectoryPoints.Add(point);  
           }  
           distance = 20.0f;  
           theta = 30;  
      }  
      void UpdateTrajectory()  
      {  
           float initialVelocity = Mathf.Sqrt((distance * -Physics.gravity.y)/(Mathf.Sin(2.0f * theta * Mathf.Deg2Rad)));  
           float initialVelocityX = initialVelocity * Mathf.Cos(theta * Mathf.Deg2Rad);  
           float initialVelocityY = initialVelocity * Mathf.Sin(theta * Mathf.Deg2Rad);  
           float tof = (- initialVelocityY - initialVelocityY) / Physics.gravity.y;  
           float delTime = tof / _numOfPoints;  
           float timeElapsed = 0.0f;  
           for (int index = 0; index < _numOfPoints; index++)  
           {  
                timeElapsed += delTime;  
                GameObject point = _trajectoryPoints[index];  
                point.transform.position = gameObject.transform.position + gameObject.transform.TransformVector(Vector3.right) * (initialVelocityX * timeElapsed)  
                     + gameObject.transform.TransformVector(Vector3.up) * ((0.5f * Physics.gravity.y * timeElapsed * timeElapsed) + (initialVelocityY * timeElapsed));  
                     ;  
           }  
      }  
      IEnumerator Fire()  
      {  
           GameObject missile = Instantiate(Resources.Load("prefabs/missile")) as GameObject;  
           float initialVelocity = Mathf.Sqrt((distance * -Physics.gravity.y)/(Mathf.Sin(2 * theta * Mathf.Deg2Rad)));  
           float initialVelocityX = initialVelocity * Mathf.Cos(theta * Mathf.Deg2Rad);  
           float initialVelocityY = initialVelocity * Mathf.Sin(theta * Mathf.Deg2Rad);  
           missile.transform.position = gameObject.transform.position;  
           missile.GetComponent<Rigidbody>().velocity = new Vector3(initialVelocityX, initialVelocityY, 0.0f);  
           float timeElapsed = 0.0f;  
           while(missile.activeInHierarchy)  
           {  
                timeElapsed += Time.deltaTime;  
                missile.transform.position = gameObject.transform.position + gameObject.transform.TransformVector(Vector3.right) * (initialVelocityX * timeElapsed)  
                     + gameObject.transform.TransformVector(Vector3.up) * ((0.5f * Physics.gravity.y * timeElapsed * timeElapsed) + (initialVelocityY * timeElapsed));  
                ;  
                yield return null;  
           }  
      }  
      void Update()  
      {  
           UpdateTrajectory();  
           if (Input.GetMouseButtonDown(0))  
           {  
                StartCoroutine("Fire");  
           }  
      }  
 }  

attach the object of interest in fire method...

HAPPY CODING 🙂

Add a private float variable _shakeDecay in camera script and declare a public function shake. Call this function when shake has to be activated.

 public void Shake()  
      {  
           _shakeDecay = 0f;  
           StopCoroutine("CameraShake");  
           StartCoroutine("CameraShake");  
      }  
      IEnumerator CameraShake()  
      {  
           while (_shakeDecay < 2f)  
           {  
                _shakeDecay += Time.deltaTime;  
                transform.position = transform.position + new Vector3(Random.Range(-0.2f, 0.2f), Random.Range(-0.2f, 0.2f), Random.Range(-0.2f, 0.2f));  
                 yield return null;  
           }  
           yield return null;  
      }  

When i was searching thru the internet i wasn’t able to find a perfect tutorial that gives a solution. After googling around and watching lot of tutorials. Im writing this which i found will be useful for many others. And it works perfectly fine as long as you know the object velocity and its start position.

Vec2 startPosition = getBallPosition(); //object start position

Vec2 ballVelocity = //ur object start velocity

ballVelocity.x *= PTM_RATIO;   //converting meter to pixel

float gravityInPixels = GRAVITY*PTM_RATIO;

int granularity = 20;

for (int index = 0; index < granularity; index++)

{

Sprite * path = Sprite::create("aimline.png");

path->setAnchorPoint(Vec2(0.0, 0.0));

if (_aimingLine == nullptr)

{

_aimingLine = Sprite::create();

addChild(_aimingLine);

}

_aimingLine->addChild(path);

path->setScale(5.0/path->getBoundingBox().size.width, 5.0/path-      >getBoundingBox().size.height);

ballVelocity.y += gravityInPixels / granularity;

startPosition.x += ballVelocity.x / granularity;

startPosition.y += ballVelocity.y / granularity;

path->setPositionX(startPosition.x);

path->setPositionY(startPosition.y);

}

CameraShake.h

#define __MyCppGame__CameraShake__

#include "cocos2d.h"

using namespace cocos2d;

class CameraShake : public ActionInterval

{

public:

CameraShake();

CREATE_FUNC(CameraShake);

virtual bool init();

bool initWithDuration(float d, float strength_x, float strength_y );

 

virtual void startWithTarget(Node *pTarget);

virtual void update(float time);

virtual void stop(void);

virtual ActionInterval* reverse() const override{return nullptr;};

virtual ActionInterval *clone() const override{return nullptr;};

protected:

float _initial_x, _initial_y;

float _strength_x, _strength_y;

 

Node * m_pTarget;

};

#endif /* defined(__MyCppGame__CameraShake__) */

————————————————————————————————————

#include "CameraShake.h"
#include "cocos2d.h"
#include "../Constants.h"
#include "../lib/Utility.h"

CameraShake::CameraShake() : _strength_x(0), _strength_y(0), _initial_x(0), _initial_y(0)
{

}

bool CameraShake::init()
{

return true;
}

bool CameraShake::initWithDuration(float duration, float strength_x, float strength_y)
{
if (CCActionInterval::initWithDuration(duration))
{
_strength_x = strength_x;

_strength_y = strength_y;

return true;

}

return false;
}

void CameraShake::update(float time)
{
float randx = Utility::fgRangeRand( -_strength_x, _strength_x );

float randy = Utility::fgRangeRand( -_strength_y, _strength_y );

m_pTarget->setPosition( Vec2(_initial_x + randx, _initial_y + randy));
}

void CameraShake::startWithTarget(Node *pTarget)
{
CCActionInterval::startWithTarget( pTarget );

_initial_x = Utility::getDevicePositionX(REF_GAME_WIDTH/2.0);

_initial_y = Utility::getDevicePositionY(REF_GAME_HEIGHT/2.0);

m_pTarget = pTarget;
}

void CameraShake::stop(void)
{
m_pTarget->setPosition( Vec2( _initial_x, _initial_y ) );

CCActionInterval::stop();
}

————————————————————————————————————-

Use Case :

CameraShake * camShake = CameraShake::create();
camShake->initWithDuration(0.25, Utility::getDevicePositionX(2.0), Utility::getDevicePositionY(2.0));
runAction(camShake);

————————————————————————————————————-

I guess the code is self explanatory

 

Happy Coding 🙂

# ifndef _COLLISION_LISTENER_   
# define _COLLISION_LISTENER_   
# include <vector>   
# include "Box2D\Box2D.h"   
#include "Box2D\Dynamics\b2WorldCallbacks.h"   

class CollisionListener : public b2ContactListener   
{        
   std::vector<b2Contact*> _contacts;   

   public:        
   /// Called when two fixtures begin to touch.        
   virtual void BeginContact(b2Contact* contact);
   
   /// Called when two fixtures cease to touch.        
   virtual void EndContact(b2Contact* contact);

   //explicitly called from main every frame         
   void ResolveContacts();        

   bool ResolveContact( b2Contact * contact);   

};
# endif 

.cpp file

#include "CollisionListener.h"
#include "Physics/PhysicsSprite.h"   
void CollisionListener::BeginContact( b2Contact* contact )   
{        
   std::vector<b2Contact*>::iterator iter = std::find(_contacts.begin(), _contacts.end(), contact);        
   if (iter != _contacts.end())        
   {             
      _contacts.erase(iter);        
   }        
   _contacts.push_back(contact);   
}   
void CollisionListener::EndContact( b2Contact* contact )   
{        
   std::vector<b2Contact*>::iterator iter = _contacts.begin();        
   iter = std::find(_contacts.begin(), _contacts.end(), contact);        
   if( iter != _contacts.end())        
   {             
      _contacts.erase(iter);        
   }   
}   

//must be called every frame
void CollisionListener::ResolveContacts()   
{        
   std::vector<b2Contact*>::iterator iter;        
   for (iter = _contacts.begin(); iter != _contacts.end();)        
   {             
      if(ResolveContact(*iter))             
      {                  
         iter  = _contacts.erase(iter);             
      }             
      else             
      {                  
         ++iter;             
      }        
   }   
}   

bool CollisionListener::ResolveContact( b2Contact * contact)   
{        
   PhysicsSprite * phySpriteA;        
   PhysicsSprite * phySpriteB;        
   b2Body * body = contact->GetFixtureA()->GetBody();        

   if(body != NULL && body->GetUserData() != NULL)        
   {             
    // do resolve             
     phySpriteA = (PhysicsSprite*)(body->GetUserData());         
   }        
   else        
  {             
    return true;        
  }        

   body = contact->GetFixtureB()->GetBody();        
   if(body != NULL && body->GetUserData() != NULL)        
   {             
     //do resolve             
     phySpriteB = (PhysicsSprite*)(body->GetUserData());         
   }        
   else        
  {             
     return true;        
  }        

//In your custom physics sprite class, you must have a GetObjectId() to determine the object 
  phySpriteA->CollidesWith(phySpriteB->GetObjectId(), phySpriteB);        
  phySpriteB->CollidesWith(phySpriteA->GetObjectId(), phySpriteA);        
  return true;   
}  
 

Initialize listener in main.cpp

 //initialize Collision listener        
_collisionListener = new CollisionListener();

//your physics world
 PhysicsEnvironment::getWorld()->SetContactListener(_collisionListener);  
//on update do this
_collisionListener->ResolveContacts(); 
Now whenever two objects collide the function collides with will be triggered in both the classes. Lets see an example from player class

Player.h

//virtual fns        
virtual void CollidesWith(ENUM_OBJECT object, PhysicsSprite * phySprite);  

Player.cpp

void Player::CollidesWith( ENUM_OBJECT object, PhysicsSprite * phySprite)  
{        
   switch (object)        
   {        
      case e_Crate:             
      {                
          //do add your logic here - when player collides with crate           
      }             
      break;   
     
     default:             
     break;        
    }   
}  

All the stuffs mentioned here are not explained in detail. If required put a comment, will reply asap. Happy Coding 🙂

Its so simple as that in Cocos2Dx using rapidJson( in-built json lib )

Lets see how to read json files in cocos2dx

std::ostringstream jsonFileName;

jsonFileName << "name.json";

std::string path = FileUtils::getInstance()->fullPathForFilename(fileName);

std::string jsonData = FileUtils::getInstance()->getStringFromFile(path);

 
rapidjson::Document document;

document.Parse<0>(jsonData.c_str());

Now you can get the contents of json file using its KEY

rapidJson::value content = document["your key"];

Its the basic for the localisation as well.

//------------------------------------------------LanguageManager.h

#include <string>

using std::string;

 
#include "cocos2d.h"

USING_NS_CC;

 
#include "../../cocos2d/external/json/document.h"

#include "../../cocos2d/external/json/rapidjson.h"

 
using namespace rapidjson; // library that we use for json parsing

 
class LanguageManager

{

    Document document; // current document with language data

    LanguageManager(); // constructor is private

    static LanguageManager* _instance;

public:

    static LanguageManager* getInstance();

    string getStringForKey(string key);

    static string getString(string key);

};

 

//-----------------------------------------------LanguageManager.cpp

#include "LanguageManager.h"

 
LanguageManager* LanguageManager::_instance = 0;

 
LanguageManager::LanguageManager()

{

    string fileName;

    // detect current language

//    switch(CCApplication::getInstance()->getCurrentLanguage())

    switch(LanguageType::JAPANESE)

    {

        case LanguageType::ENGLISH:

            fileName = "en.json";

            break;

        case LanguageType::RUSSIAN:

            fileName = "ru.json";

            break;

        case  LanguageType::CHINESE:

            fileName = "cn.json";

            break;

        case  LanguageType::FRENCH:

            fileName = "fr.json";

            break;

        case  LanguageType::ITALIAN:

            fileName = "it.json";

            break;

        case  LanguageType::GERMAN:

            fileName = "ge.json";

            break;

        case  LanguageType::SPANISH:

            fileName = "sp.json";

            break;

        case LanguageType:: DUTCH:

            fileName = "du.json";

            break;

        case  LanguageType::KOREAN:

            fileName = "ko.json";

            break;

        case  LanguageType::JAPANESE:

            fileName = "jp.json";

            break;

        case  LanguageType::HUNGARIAN:

            fileName = "hu.json";

            break;

        case  LanguageType::PORTUGUESE:

            fileName = "pt.json";

            break;

        case  LanguageType::ARABIC:

            fileName = "ar.json";

            break;

        case  LanguageType::NORWEGIAN:

            fileName = "nw.json";

            break;

        case  LanguageType::POLISH:

            fileName = "po.json";

            break;

        default:

            CCLOG("Unknown language. Use english");

            fileName = "en.json";

            break;

    };

 
    // below we open, read and parse language data file with rapidjson library

    string clearContent = FileUtils::getInstance()->getStringFromFile(fileName);

 
    document.Parse<0>(clearContent.c_str());

    if(document.HasParseError())

    {

        CCLOG("Language file parsing error!");

        return;

    }

}

 
LanguageManager* LanguageManager::getInstance()

{

    if(!_instance)

        _instance = new LanguageManager();

    return _instance;

}

 
string LanguageManager::getStringForKey(string key)

{

    /* Better Approach

     -------------------------------

 
     std::string ret;

     std::string ss;

     int n, size=100;

     bool b=false;

     va_list marker;

 
     std::string fmt = document[key.c_str()].GetString();

 
     while (!b)

     {

     ss.resize(size);

     va_start(marker, key);

     n = vsnprintf((char*)ss.c_str(), size, fmt.c_str(), marker);

     va_end(marker);

     if ((n>0) && ((b=(n<size))==true)) ss.resize(n); else size*=2;

     }

     ret += ss;

 
     return ret;

     */

 
    //Simple approach

    return document[key.c_str()].GetString();

}

 
string  LanguageManager::getString(string key)

{

    return getInstance()->getStringForKey(key);

}

 
//--------------------------------------------------------------

 
 
Sample Code:

-------------

 
    LanguageManager * man = LanguageManager::getInstance();

 
    std::string info = man->getStringForKey("Hello");

         TextField * txt = some text field reference

          txt->setText(info.c_str());

 
//----------------------------------------------------------------------------------------------------

 
Sample Json file

-------------------

 
{

    "Hello" : "language of ur choice using some translator"

}

 
//----------------------------------------------------------------------------------------------------

 

Cheers

Happy Coding 🙂