120 lines
2.6 KiB
C#
120 lines
2.6 KiB
C#
using UnityEngine;
|
|
|
|
public class PlayerHeadController : MonoBehaviour
|
|
{
|
|
public Transform Head;
|
|
public Transform CameraTransform;
|
|
|
|
public Transform BodyTransform;
|
|
|
|
|
|
public float ThrowForce;
|
|
public float PickupDistance;
|
|
public bool isHoldingHead;
|
|
|
|
private Rigidbody m_headRigidbody;
|
|
|
|
private Vector3 m_headInitialLocalPos;
|
|
private Quaternion m_headInitialLocalRot;
|
|
|
|
private Animator animator;
|
|
private PlayerInputController input;
|
|
|
|
private void Awake()
|
|
{
|
|
animator = GetComponent<Animator>();
|
|
input = GetComponent<PlayerInputController>();
|
|
}
|
|
|
|
void Start()
|
|
{
|
|
Cursor.lockState = CursorLockMode.Locked;
|
|
|
|
Vector3 offset = new Vector3(0f, -0.5f, 0.5f);
|
|
|
|
m_headInitialLocalPos = BodyTransform.localPosition + offset;
|
|
m_headInitialLocalRot = BodyTransform.localRotation;
|
|
m_headRigidbody = Head.GetComponent<Rigidbody>();
|
|
|
|
Head.SetParent(null);
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (input.HeadInteractionPressed)
|
|
{
|
|
InteractHead();
|
|
}
|
|
|
|
if (input.ThrowPressed)
|
|
{
|
|
ThrowHead();
|
|
}
|
|
}
|
|
|
|
private void InteractHead()
|
|
{
|
|
if (!isHoldingHead)
|
|
TryPickupHead();
|
|
else
|
|
DropHead();
|
|
}
|
|
|
|
private void DropHead()
|
|
{
|
|
Debug.Log("DropHead");
|
|
animator.SetTrigger("Throw");
|
|
|
|
isHoldingHead = false;
|
|
|
|
Head.SetParent(null);
|
|
|
|
m_headRigidbody = Head.gameObject.AddComponent<Rigidbody>();
|
|
m_headRigidbody.mass = 1f;
|
|
|
|
m_headRigidbody.constraints =
|
|
RigidbodyConstraints.FreezeRotationX |
|
|
RigidbodyConstraints.FreezeRotationZ |
|
|
RigidbodyConstraints.FreezeRotationY;
|
|
}
|
|
|
|
private void ThrowHead()
|
|
{
|
|
Debug.Log("ThrowHead");
|
|
if (!isHoldingHead)
|
|
return;
|
|
|
|
DropHead();
|
|
|
|
m_headRigidbody.AddForce(CameraTransform.forward * ThrowForce, ForceMode.Impulse);
|
|
}
|
|
|
|
private void TryPickupHead()
|
|
{
|
|
if (isHoldingHead)
|
|
return;
|
|
|
|
float distance = Vector3.Distance(transform.position, Head.position);
|
|
|
|
if (distance <= PickupDistance)
|
|
{
|
|
PickupHead();
|
|
}
|
|
}
|
|
|
|
private void PickupHead()
|
|
{
|
|
Debug.Log("PickupHead");
|
|
isHoldingHead = true;
|
|
|
|
if (m_headRigidbody != null)
|
|
{
|
|
Destroy(m_headRigidbody);
|
|
}
|
|
|
|
Head.SetParent(transform);
|
|
|
|
Head.localPosition = m_headInitialLocalPos;
|
|
Head.localRotation = m_headInitialLocalRot;
|
|
}
|
|
} |