Search code examples
cocos2d-xcocos2d-x-3.0android-vibrationiphone-vibrate

How to add vibration to cocos2d-x 3.2 on Android and iOS devices?


I want to vibrate my device in one of my slider functionality, using cocos2d-x 3.2.

I followed some of reference links regarding this on the official forums but I'm still stumped.

Can anyone help me?


Solution

  • After Searching a lot , Finally i am done with my Vibrate Function in Cocos2d-x 3.2 for android.

    There is one Vibrator Class.

    Vibrator.h

    #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    #include <jni.h>
    #include <android/log.h>
    #include "platform/android/jni/JniHelper.h"
    #endif
    #define  CLASS_NAME "org/cocos2dx/lib/Cocos2dxHelper"
    class Vibrator
    {
    public:
    static void Vibrate(int time);
    static void CancelVibrate();
    };
    #endif
    

    Vibrator.cpp

    #include "Vibrator.h"
    
    void Vibrator::Vibrate(int time)
    {
    #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    JniMethodInfo t;
    
    if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "vibrate", "(I)V"))
    {
        t.env->CallStaticVoidMethod(t.classID, t.methodID, time);
        t.env->DeleteLocalRef(t.classID);
    }
    #endif
    }
    void Vibrator::CancelVibrate()
    { 
    #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    JniMethodInfo t;
    if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "cancelVibrate", "()V"))
    {
        t.env->CallStaticVoidMethod(t.classID, t.methodID);
        t.env->DeleteLocalRef(t.classID);
    }
    #endif
    }
    

    => in AndroidManifest.xml : add below permission .

    => in src/org/cocos2dx/lib/Cocos2dxHelper.java file : add below 2 methods

    first import => import android.os.Vibrator;

    then , add these 2 methods

    public static void vibrate ( int vibrateTime)  {
        Vibrator vib = (Vibrator) sActivity.getSystemService (Service.VIBRATOR_SERVICE);
        vib.vibrate (vibrateTime);
    }
    
    public  static  void  cancelVibrate () {
        Vibrator vib = (Vibrator) sActivity.getSystemService  (Service.VIBRATOR_SERVICE);
        vib.cancel ();
    }
    

    Now, Whenever we want to use Vibrate Function we just have to include this Vibrator Class & Simply Calling it as below .

    Vibrator::Vibrate(50);
    

    For Disabling it,

    Vibrator::CancelVibrate(); 
    

    in won't work in Tab as it does not having Vibrator in it .