Rewired 目前仅支持游戏手柄振动和 DualSense 触发器触觉反馈。
准备工作:
首先我们需要安装插件Rewired,并把InputManager挂载在场景的物体下。Window=>Rewired=>Create=>Input Manager(in scene)
或者你也可以创建一个prefab并用Initializar创建一个Input Manager在场景中。
按下图点击场景中的Rewired Input Manager并且点击LanuchRewiredEditor编辑一下数据。
点击左下角New,创建一个Player出来然后关掉窗口。(不需要配置其他东西)
进入正题我们可以通过两种方法来触发手柄震动。
- 通过Player
- 通过Joystick
首先创建一个脚本PlayerVibration.cs并挂载在场景下。
如何通过Player设置震动
通过播放器设置振动允许您同时设置分配给该播放器的所有操纵杆上的振动。
一般手柄是有2或者4个震动马达,此处motorIndex可以设置0到3,0号马达一般是在左边,1号马达一般在右边,2,3号马达一般在中心。
0和1号马达的震动幅度强,2,3号马达的震动幅度较弱。
using UnityEngine;
using Rewired;
public class PlayerVibration : MonoBehaviour
{
//玩家id为0
public int playerId = 0;
private Player player { get { return ReInput.players.GetPlayer(playerId); } }
// 设置分配给玩家的所有操纵杆的振动
public int motorIndex = 0; // 设置哪个马达震动,0代表第一个马达
public float motorLevel = 1.0f;// 设置马达的速度,从0到1
public float duration = 1f; // 震动的持续时间
public Joystick joystick;
private void Start()
{
joystick = ReInput.controllers.GetController<Joystick>(playerId);//获取玩家id为0的摇杆
Debug.Log(joystick.name);//输出摇杆名称
Debug.Log(joystick.vibrationMotorCount);//输出摇杆的马达的数量
}
void Update()
{
if (player.GetAnyButton())//按下任意按键触发摇杆震动
{
player.SetVibration(motorIndex, motorLevel, duration);
}
}
}
如何通过Joystick设置震动
要在操纵杆中设置振动,只需从Player类中获取它们并在每个操纵杆上设置马达电机级别。
using System.Collections;
using UnityEngine;
using Rewired;
public class PlayerVibration : MonoBehaviour
{
//玩家id为0
public int playerId = 0;
private Player player { get { return ReInput.players.GetPlayer(playerId); } }
// 设置分配给玩家的所有操纵杆的振动
public int rightMotorValue = 1; //右边摇杆的震动级别
public int leftMotorValue = 1;//左边摇杆的震动级别
private bool isVibration = false;
public Joystick joystick;
private void Start()
{
joystick = ReInput.controllers.GetController<Joystick>(playerId);//获取玩家id为0的摇杆
Debug.Log(joystick.name);//输出摇杆名称
Debug.Log(joystick.vibrationMotorCount);//输出摇杆的马达的数量
}
void Update()
{
if (player.GetAnyButton())//按下任意按键触发摇杆震动
{
isVibration = true;
}
HandleVibration();
}
public void HandleVibration()
{
if (isVibration)
{
isVibration = false;
//Joystick方法1:设置一定持续时间的振动
foreach (Joystick j in player.controllers.Joysticks)
{
if (!j.supportsVibration) continue;
if (j.vibrationMotorCount > 0) j.SetVibration(0, leftMotorValue, 1.0f); // 持续 1 秒
}
//法2法3需要携程暂停
//StartCoroutine(PlayVibration());
}
}
private IEnumerator PlayVibration()
{
// Joystick法2 : 通过马达类型设置振动
// foreach (Joystick j in player.controllers.Joysticks)
// {
// if (!j.supportsVibration) continue;
// j.SetVibration(leftMotorValue, rightMotorValue);
// }
//Joystick法3 : 通过马达索引设置振动
// foreach (Joystick j in player.controllers.Joysticks)
// {
// if (!j.supportsVibration) continue;
// if (j.vibrationMotorCount > 0) j.SetVibration(0, leftMotorValue);
// if (j.vibrationMotorCount > 1) j.SetVibration(1, rightMotorValue);
// }
yield return new WaitForSeconds(1);//等待一秒后再停止震动
//停止振动 上述法2法3都需要暂停要不然会一直震个不停,好像也不错?b( ̄▽ ̄)d
foreach (Joystick j in player.controllers.Joysticks)
{
j.StopVibration();
}
}
}
总结:
通过Player控制更方便,通过Joystick可以更加细节某些场景下可以打断震动。