using System;
using UnityEngine;
[RequireComponent(typeof(CapsuleCollider), typeof(Rigidbody))]
public class SimpleOVRMovement : MonoBehaviour
{
public bool EnableLinearMovement = true;
public bool HMDRotatesPlayer = true;
public float RotationAngle = 45.0f;
public float Speed = 0.0f;
public OVRCameraRig CameraRig;
private bool ReadyToSnapTurn;
private Rigidbody rigidbody;
private Transform CenterEye => CameraRig.centerEyeAnchor;
public event Action CameraUpdated;
private void Awake()
{
rigidbody = GetComponent<Rigidbody>();
CameraRig ??= GetComponentInChildren<OVRCameraRig>();
}
private void FixedUpdate()
{
CameraUpdated?.Invoke();
RotatePlayerToHMD();
StickMovement();
SnapTurn();
}
private void RotatePlayerToHMD()
{
if (!HMDRotatesPlayer) return;
Transform root = CameraRig.trackingSpace;
Vector3 prevPos = root.position;
Quaternion prevRot = root.rotation;
transform.rotation = Quaternion.Euler(0.0f, CenterEye.rotation.eulerAngles.y, 0.0f);
root.SetPositionAndRotation(prevPos, prevRot);
}
private void StickMovement()
{
if (!EnableLinearMovement) return;
Quaternion yRotation = Quaternion.Euler(0, CenterEye.rotation.eulerAngles.y, 0);
Vector2 primaryAxis = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick);
Vector3 moveDir = yRotation * new Vector3(primaryAxis.x, 0, primaryAxis.y);
rigidbody.MovePosition(rigidbody.position + moveDir * (Speed * Time.fixedDeltaTime));
}
private void SnapTurn()
{
float rotation = GetSnapTurnRotation();
if (rotation != 0 && ReadyToSnapTurn)
{
ReadyToSnapTurn = false;
transform.RotateAround(CenterEye.position, Vector3.up, rotation);
}
else if (rotation == 0)
{
ReadyToSnapTurn = true;
}
}
private float GetSnapTurnRotation()
{
float xInput = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick).x;
return xInput < -0.5f ? -RotationAngle : xInput > 0.5f ? RotationAngle : 0f;
}
}
OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick);
PrimaryThumbstick은 왼쪽 컨트롤러의 조이스틱을 뜻합니다.
OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick).x;
SecondaryThumstick은 오른쪽 컨트롤러의 조이스틱을 뜻합니다.