標籤:unity android vibrator
要在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表示不重複。
Parameters
pattern 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原生的震動(簡單)