Camera Shake in Cocos2dx 3.x

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 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *