最近项目需要功能:player上车后,手柄可以控制汽车移动。
实现这个功能比较简单,主要是通过手指的位置计算出手指与轴(Vector2.up)之间的夹角。
在使用之前需要在Action中添加bool属性的TrackPadTouch,并把这个属性绑定在圆盘上。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Valve.VR;
public enum UseObject
{
Car,
Player
}
[ExecuteInEditMode]
public class ControlCar: MonoBehaviour
{
public GameObject Cube;
public Transform player;
public Camera scenceCamera;
private UseObject useObject = UseObject.Player;
private float mixDistance=1;
private Vector2 fingerPos;
void Update()
{
if (SteamVR_Actions._default.TrackPadTouch.GetState(SteamVR_Input_Sources.Any))
{
fingerPos = SteamVR_Actions._default.TrackPadPos.lastAxis;
ComputeDistance();
ControlMove();
}
}
private float CountAngle()
{
float Angle = Mathf.Acos(Vector2.Dot(fingerPos, Vector3.up))*Mathf.Rad2Deg;
Angle = fingerPos.x < 0 ? - Angle: Angle;
return Angle;
}
private void ControlMove()
{
switch (useObject)
{
case UseObject.Player:
player.position = Vector3.MoveTowards(player.position,
player.position + new Vector3(fingerPos.x,
0, fingerPos.y), Time.deltaTime);
break;
case UseObject.Car:
Cube.transform.position = Vector3.MoveTowards(Cube.transform.position, Cube.transform.position + Cube.transform.forward, Time.deltaTime);
ControlRotate(Cube.gameObject, SteamVR_Actions._default.TrackPadPos.lastAxis);
break;
}
}
private void ControlRotate(GameObject Obj, Vector3 Pos)
{
Vector3 tragt = new Vector3(Obj.transform.localEulerAngles.x, CountAngle(), Obj.transform.localEulerAngles.z);
Obj.transform.rotation = Quaternion.RotateTowards(Obj.transform.rotation, Quaternion.Euler(0, CountAngle(),0), Time.deltaTime * 100);
}
private void ComputeDistance()
{
float distance = Vector3.Distance(player.position, Cube.transform.position);
if (distance < mixDistance)
{
player.gameObject.SetActive(false);
scenceCamera.gameObject.SetActive(true);
useObject=UseObject.Car;
}
}
private void OnDrawGizmos()
{
Gizmos.DrawLine(Vector3.zero, Quaternion.Euler(0,-45,0)*Vector3.right);
Gizmos.DrawLine(Vector3.zero, Cube.transform.position);
}
}