Unity调用Android原生的震动(简单)

要在unity中调用Android系统的震动,需要一个Vibrator类 ,通过AndroidManifest.xml文件设置权限了

如下:

<uses-permission android:name="android.permission.VIBRATE" />在这里先给贴出英文文档及大概的翻译 :

Class that operates the vibrator on the device.If your process exits, any vibration you started with will stop. Vibrator类用来操作设备上的震动,,如果你的线程退出了,那么启动的震动也会停止

Pass in an array of ints that are the durations for which to turn on or off the vibrator in milliseconds. The first value indicates the number of milliseconds to wait before turning the vibrator on. The next value indicates the number of milliseconds for which to keep the vibrator on before turning it off. Subsequent values alternate between durations in milliseconds to turn the vibrator off or to turn the vibrator on.

传递一个整型数组作为关闭和开启震动的持续时间,以毫秒为单位。第一个值表示等待震动开启的毫秒数,下一个值表示保持震动的毫秒数,这个序列值交替表示震动关闭和开启的毫秒数To cause the pattern to repeat, pass the index into the pattern array at which to start the repeat, or -1 to disable repeating.为了重复的按设定的节奏震动,传递index参数表示重复次数,用-1表示不重复。Parameterspattern an array of longs of times for which to turn the vibrator on or off.repeat the index into pattern at which to repeat, or -1 if you don’t want to repeat.

上代码:

public void StartShock( long [] mpattern,int index ) {vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);long [] pattern = {100,400,100,400}; pattern = mpattern;vibrator.vibrate(pattern,index);}这里设置两个参数,以便于在unity中灵活定义震动;

同时还有:

public void onStop(){super.onStop();vibrator.cancel();}

之后把自己的Android工程Clean一下,然后打出自己的 jar包(或者用命令行: jar -cvf myclass.jar *(打包步骤略去)),把打好的jar包放在unity工程中(“Plugins/Android/libs”);

最好我们回到unity,新建一个C#脚本,

贴出代码 :

public static void PlayShock(){//#if UNITY_ANDROID && !UNITY_EDITORif (mshockEnable){long[] shock = new long[] { 100, 1000 };using (AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer")){AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");jo.Call("StartShock", shock,-1);}}//#endif}

通过此方法来调用Android的原生震动。

此教程比较简单,有好的建议,欢迎 轻喷!

去陌生的街角,去做一切我们曾经或现在也很想做的事情,

Unity调用Android原生的震动(简单)

相关文章:

你感兴趣的文章:

标签云: