这个震动需要调用adnroid系统的方法,所以需要C++调用java,JNI这里就不多做介绍了,需要的可以自己去查找下相关资料,如果你只是需要实现这个功能,相信你看完本文,应该就OK了!
1.首先,修改你的android项目的AndroidManifest.xml文件,给app增加震动权限
2.修改android项目源文件src/org/cocos2dx/lib/Cocos2dxSound.java增加震动方法,调用android底层振动器
/*** @param time 震动时间*/public void vibrate(long time){ Vibratorv=(Vibrator)mContext.getSystemService(Context.VIBRATOR_SERVICE); v.vibrate(time);}/*** @param pattern 震动时间数组 EG:{500,200,500,300}* @param repeat 重复次数*/public void vibrateWithPattern(long pattern[], int repeat){ Vibratorv=(Vibrator)mContext.getSystemService(Context.VIBRATOR_SERVICE); v.vibrate(pattern, repeat);}/*** 取消震动*/public void cancelVibrate(){ Vibratorv=(Vibrator)mContext.getSystemService(Context.VIBRATOR_SERVICE); v.cancel();}
3.至此,java项目中的修改就OK啦,下面就是在Cocos2d-x中增加JNI方法让C++去掉用Java的震动方法就OK啦!
3.1.修改 libCocosDenshion项目中CocosDenshionandroidjni文件夹下的SimpleAudioEngineJni.h和SimpleAudioEngineJni.cpp方法
#ifndef __SIMPLE_AUDIO_ENGINE_JNI__#define __SIMPLE_AUDIO_ENGINE_JNI__#includeextern"C"{ ...... // add these menthod externvoidvibrateJNI(longlongtime); externvoidvibrateWithPatternJNI(longlongpattern[],intrepeat); externvoidcancelVibrateJNI();}#endif // __SIMPLE_AUDIO_ENGINE_JNI__
// add these jni menthodvoid vibrateJNI(long longtime){ JniMethodInfo methodInfo; if(!getStaticMethodInfo(methodInfo,"vibrate","(J)V")) { return; } methodInfo.env->CallStaticVoidMethod(methodInfo.classID,methodInfo.methodID,time); methodInfo.env->DeleteLocalRef(methodInfo.classID);}void vibrateWithPatternJNI(long longpattern[], int repeat){ JniMethodInfo methodInfo; if(!getStaticMethodInfo(methodInfo,"vibrateWithPattern","([JI)V")) { return; } int elements=sizeof(pattern); jlongArray jLongArray=methodInfo.env->NewLongArray(elements); methodInfo.env->SetLongArrayRegion(jLongArray,0,elements,(jlong*)pattern); methodInfo.env->CallStaticVoidMethod(methodInfo.classID,methodInfo.methodID,jLongArray,repeat); methodInfo.env->DeleteLocalRef(methodInfo.classID);}void cancelVibrateJNI(){ JniMethodInfo methodInfo; if(!getStaticMethodInfo(methodInfo,"cancelVibrate","()V")) { return; } methodInfo.env->CallStaticVoidMethod(methodInfo.classID,methodInfo.methodID); methodInfo.env->DeleteLocalRef(methodInfo.classID);}
3.2修改CocosDenshion/include/SimpleAudioEngine.h增加如下方法.
void vibrate(long longtime);void vibrateWithPattern(long longpattern[],int repeat);void cancelVibrate();
3.3修改CocosDenshion/android/SimpleAudioEngine.cpp增加调用JNI的如下方法。
void SimpleAudioEngine::vibrate(long longtime){ vibrateJNI(time);}void SimpleAudioEngine::vibrateWithPattern(long longpattern[],intrepeat){ vibrateWithPatternJNI(pattern, repeat);}void SimpleAudioEngine::cancelVibrate(){ cancelVibrateJNI();}
4.至此,代码上的修改都OK啦,在游戏中需要使用震动的地方调用。
CocosDenshion::SimpleAudioEngine::sharedEngine()->vibrate(time);CocosDenshion::SimpleAudioEngine::sharedEngine()->vibrateWithPattern(pattern, repeat);
Cancle Vibrate Using this!
CocosDenshion::SimpleAudioEngine::sharedEngine()->cancelVibrate();
5.如果需要修改后的代码,请移步原帖。