using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Valve.VR;
public class AdvancedTouchpadMove : MonoBehaviour
{
[Header("移动参数")]
public float minSpeed = 0.8f; // 最小移动速度(触控板中心)
public float maxSpeed = 3.0f; // 最大移动速度(触控板边缘)
public float deadZoneRadius = 0.2f;// 死区半径(比例值)
public float accelerationCurve = 1.5f; // 加速曲线指数
[Header("触觉反馈")]
public float hapticInterval = 0.3f; // 触觉脉冲间隔
private Vector2 touchPosition;
private float lastHapticTime;
private bool isTouching;
void Update()
{
HandleTouchInput();
ApplyMovement();
}
private void HandleTouchInput()
{
// 获取触控板触摸状态(需在SteamVR Input设置二元触摸检测)
isTouching = SteamVR_Actions.default_TouchpadTouch.GetState(SteamVR_Input_Sources.RightHand);
if (isTouching)
{
// 获取触控板坐标(归一化值,中心为(0,0))
touchPosition = SteamVR_Actions.default_TrackpadPosition.GetAxis(SteamVR_Input_Sources.RightHand);
// 触觉脉冲反馈
if (Time.time - lastHapticTime > hapticInterval)
{
SteamVR_Actions.default_Haptic.Execute(0, 0.05f, 100, 0.2f, SteamVR_Input_Sources.RightHand);
lastHapticTime = Time.time;
}
}
}
private void ApplyMovement()
{
if (!isTouching) return;
// 计算触控点极坐标
float touchDistance = touchPosition.magnitude;
float touchAngle = Mathf.Atan2(touchPosition.x, touchPosition.y) * Mathf.Rad2Deg;
// 死区过滤
if (touchDistance < deadZoneRadius) return;
// 速度计算(非线性曲线)
float speedFactor = Mathf.Pow((touchDistance - deadZoneRadius) / (1 - deadZoneRadius), accelerationCurve);
float currentSpeed = Mathf.Lerp(minSpeed, maxSpeed, speedFactor);
// 方向计算(基于摄像机朝向)
Debug.Log(touchAngle);
Vector3 moveDirection = Quaternion.Euler(0, touchAngle, 0) * Camera.main.transform.forward;
moveDirection.y = 0;
// 执行移动
transform.position += moveDirection.normalized * currentSpeed * Time.deltaTime;
// 动态视场调节(防眩晕)
AdjustFOVBasedOnSpeed(currentSpeed);
}
private void AdjustFOVBasedOnSpeed(float speed)
{
float targetFOV = Mathf.Lerp(90f, 75f, speed / maxSpeed);
Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, targetFOV, 5f * Time.deltaTime);
}
}
挂在[CameraRig]上
配置: