コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】Input System でコントローラを振動させるサンプル

概要

using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;

public sealed class Example : MonoBehaviour
{
    private void Update()
    {
        var gamepad = Gamepad.current;

        // A ボタンが押されたら
        if ( gamepad.aButton.wasPressedThisFrame )
        {
            // 低周波(左)モーターの強さを 1、
            // 高周波(右)モーターの強さを 0 で振動させる
            StartCoroutine( Vibration( 1, 0 ) );
        }
        // B ボタンが押されたら
        else if ( gamepad.bButton.wasPressedThisFrame )
        {
            // 低周波(左)モーターの強さを 0、
            // 高周波(右)モーターの強さを 1 で振動させる
            StartCoroutine( Vibration( 0, 1 ) );
        }
    }

    private static IEnumerator Vibration
    (
        float lowFrequency, // 低周波(左)モーターの強さ(0.0 ~ 1.0)
        float highFrequency // 高周波(右)モーターの強さ(0.0 ~ 1.0)
    )
    {
        var gamepad = Gamepad.current;
        gamepad.SetMotorSpeeds( lowFrequency, highFrequency );
        yield return new WaitForSeconds( 1f ); // 1 秒間振動させる
        gamepad.SetMotorSpeeds( 0, 0 );
    }
}
  • Unity 2020.3.17f1、Xbox 360 コントローラで動作確認済み
  • Switch のプロコンだと振動しなかった