holopy3/Assets/Scripts/PlayerController.cs
2020-12-10 15:25:12 +01:00

94 lines
2.7 KiB
C#

using UnityEngine;
using Valve.VR;
public class PlayerController : MonoBehaviour
{
public LayerMask Ground;
public LayerMask NoGoArea;
public float Speed = 1.0f;
public Material BodyMat;
public SteamVR_Action_Boolean MovePress = null;
public SteamVR_Action_Vector2 MoveDirection = null;
private RaycastHit hit;
private Camera VRCam;
private GameObject Body;
void Start()
{
VRCam = GetComponentInChildren<Camera>();
Body = GameObject.CreatePrimitive(PrimitiveType.Capsule);
Body.transform.parent = transform;
Body.name = "Body";
Body.layer = 10;
Body.tag = "PlayerBody";
MeshRenderer mr = Body.GetComponent<MeshRenderer>();
mr.material = BodyMat;
Body.AddComponent<SmileyTrigger>();
Body.AddComponent<Fluorescein>();
Body.AddComponent<TurnAround>();
gameObject.AddComponent<FallDownTrigger>();
}
void Update()
{
CheckGroundHeight();
// If button pressed
if (MovePress.state)
{
CalculateMovement();
}
}
private void CheckGroundHeight()
{
if (Physics.Raycast(VRCam.transform.position, Vector3.down, out hit, Mathf.Infinity, Ground))
{
transform.position = new Vector3(transform.position.x, hit.transform.position.y, transform.position.z);
Body.transform.localScale = new Vector3(0.5f, Vector3.Distance(VRCam.transform.position, hit.point) / 2, 0.5f);
Body.transform.position = new Vector3(hit.point.x, hit.point.y + Vector3.Distance(VRCam.transform.position, hit.point) / 2, hit.point.z);
}
else
{
transform.Translate(9.81f * Time.deltaTime * Vector3.down);
}
}
private void CalculateMovement()
{
// Figure out movement orientation
Vector3 orientationEuler = new Vector3(0, VRCam.transform.eulerAngles.y, 0);
Quaternion orientation = Quaternion.Euler(orientationEuler);
Vector3 movement = Vector3.zero;
if (MovePress.state)
{
movement += orientation * (MoveDirection.axis.x * Vector3.right);
movement += orientation * (MoveDirection.axis.y * Vector3.forward);
}
// Prevent walking trhrough walls
Ray eyeRay = new Ray(VRCam.transform.position, movement);
Ray kneeRay = new Ray(VRCam.transform.position - Vector3.up, movement);
if (!Physics.Raycast(eyeRay, out RaycastHit eyeHit, 0.5f, NoGoArea))
{
if (!Physics.Raycast(kneeRay, out RaycastHit kneeHit, 0.5f, NoGoArea))
//Apply
transform.Translate(movement * Speed * Time.deltaTime);
}
}
}