この記事でのバージョン
Unity 2020.3.25f1
はじめに
Apple製品にはHaptic Feedbackというちょっとリッチな振動をさせる機能があります。
もちろん、iPhone等のiOS端末にも付いてる機能なのですが、
残念ながらUnityは対応しておらず、使うにはネイティブのプラグインを書く必要があります。
という事で今回は、公開される無料のライブラリやアセットを使って
ネイティブプラグインを書かずにUnity製のアプリにHaptic Feedback(振動)を実装する方法の紹介です!
Haptic Feedback
早速ですが今回はUnity-HapticFeedbackという物を使います。
導入はGitHubからZipをダウンロードしてきて解凍、
Pluginsディレクトリの下に追加するだけ。
後はC#で以下のようなコードを書くとiOS実機で振動するようになります。
//通知系の振動 HapticFeedback.NotificationOccurred(NotificationFeedbackStyle.Error); HapticFeedback.NotificationOccurred(NotificationFeedbackStyle.Success); HapticFeedback.NotificationOccurred(NotificationFeedbackStyle.Warning); //影響?衝撃?系の振動 HapticFeedback.ImpactOccurred(ImpactFeedbackStyle.Light); HapticFeedback.ImpactOccurred(ImpactFeedbackStyle.Medium); HapticFeedback.ImpactOccurred(ImpactFeedbackStyle.Heavy); HapticFeedback.ImpactOccurred(ImpactFeedbackStyle.Rigid); HapticFeedback.ImpactOccurred(ImpactFeedbackStyle.Soft); //短い振動 HapticFeedback.SelectionChanged();
なお、振動の種類については以下のページで確認できます。
(Playを押すと、どんな振動か音で確かめられる)
Haptics - User Interaction - iOS - Human Interface Guidelines - Apple Developer
ちなみにアセットストアにもCore Haptics Plugin for iOS 13+という無料アセットがありました。
(有料の物であれば他にもありそうでしたが未確認)
Core Haptics Plugin for iOS 13+ | Integration | Unity Asset Store |
こちらは先程のように振動の種類を指定しての振動は出来ませんが、
強さや鋭さ、時間を指定して細かな振動させる事が出来ます。
//強さと鋭さを指定して振動 UnityCoreHapticsProxy.PlayTransientHaptics(intensity, sharpness); //強さと鋭さ、時間を指定して振動 UnityCoreHapticsProxy.PlayContinuousHaptics(intensity, sharpness, duration);
また、現在実行されている端末がHaptic Feedbackに対応してるかの判定も行えます。
if(UnityCoreHapticsProxy.SupportsCoreHaptics()){ //Haptic Feedbackに対応してる端末の時の処理 }