holopy3/Assets/Scripts/PlayerController.cs

97 lines
2.8 KiB
C#
Raw Permalink Normal View History

2020-12-10 14:25:12 +00:00
using UnityEngine;
using Valve.VR;
public class PlayerController : MonoBehaviour
{
public LayerMask Ground;
public LayerMask NoGoArea;
2021-01-28 12:07:52 +00:00
public float Speed = 2.0f;
2020-12-10 14:25:12 +00:00
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;
2021-01-28 12:07:52 +00:00
Body.AddComponent<Blinky>();
2020-12-12 18:29:31 +00:00
//Nur für Maze:
//Body.AddComponent<SmileyTrigger>();
//Body.AddComponent<Fluorescein>();
//Body.AddComponent<TurnAround>();
2020-12-10 14:25:12 +00:00
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);
}
}
}