How to call vibrate effect in cocos2dx environment ?



Here is simple example code to call vibrate effect in cocos2d

This sample based on C++ with Visual studio

First, create service class to call vibrate whenever you want.


[DeviceServices.h]

class DeviceServices

{

public:

DeviceServices();

~DeviceServices();


// Android vibrate effect call method

void callVibrateEffect();

};


[DeviceServices.cpp]

#include "DeviceServices.h"


DeviceServices::DeviceServices(){}

DeviceServices::~DeviceServices(){}


#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)


#include "platform/android/jni/JniHelper.h"

#include <jni.h>


// important : provide your java class path

const char* AppActivityClassName = "com/eyen/cpp/AppActivity";  


void DeviceServices::callVibrateEffect()

{

cocos2d::JniMethodInfo t;

if (cocos2d::JniHelper::getStaticMethodInfo(t, AppActivityClassName, "jniVibrateEffect", "()V"))

{

t.env->CallStaticVoidMethod(t.classID, t.methodID);

t.env->DeleteLocalRef(t.classID);

}

}


#else

void DeviceServices::callVibrateEffect() { return; }

#endif


const char* AppActivityClassName = "com/eyen/cpp/AppActivity"; 

Important : red marked is that, your vibrate implemented method in java path.

for me like this, but you might be different.



If you finished create service class,

Next step is easy, just call like below example code.


#include "DeviceServices.h"


void MainScene::hitEnermyObj()

{

// call android vibrate effect

DeviceServices::vibrateEffect();

}


All is done in C++ (cocos2dx part)


Next step is that, implement vibrate method for Android.


My java file path is "com/eyen/cpp/AppActivity" that which has contained implemented code for android vibrate


package com.eyen.cpp;

import android.os.Vibrator;
import org.cocos2dx.lib.Cocos2dxActivity;

public class AppActivity extends Cocos2dxActivity {

// main
private static AppActivity _appActiviy;

// vibrate
Vibrator mVibrator = null;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

_appActiviy = this;

mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

}

public void vibrateEffect() {
mVibrator.vibrate(80); // red marked number is that power of vibrate (bigger number is powerfull)
}

public static void jniVibrateEffect() {
_appActiviy.runOnUiThread(new Runnable() {
@Override
public void run() {
_appActiviy.vibrateEffect();
}
});
}
}

Good!

All is done, enjoy developement.


Here is a game which is used vibrated effect for android.





Download "Fast Shooter" in google playstore


Link : https://play.google.com/store/apps/details?id=com.eyen.fastshooter