Unity調用Android原生的震動(簡單)

來源:互聯網
上載者:User

標籤: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原生的震動(簡單)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.