72 lines
1.6 KiB
C#
72 lines
1.6 KiB
C#
using UnityEngine;
|
|
|
|
public class BoxPickup : MonoBehaviour
|
|
{
|
|
public Transform PlayerTransform;
|
|
public Transform CameraTransform;
|
|
public Transform HandTransform;
|
|
public float ThrowForce = 10f;
|
|
public float PickupDistance = 5f;
|
|
|
|
private bool isHeld;
|
|
private Rigidbody m_rigidbody;
|
|
private PlayerInputController input;
|
|
|
|
void Start()
|
|
{
|
|
m_rigidbody = GetComponent<Rigidbody>();
|
|
input = PlayerTransform.GetComponent<PlayerInputController>();
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (input.InteractPressed)
|
|
{
|
|
if (!isHeld)
|
|
TryPickup();
|
|
else
|
|
Drop();
|
|
}
|
|
|
|
if (input.ThrowPressed)
|
|
Throw();
|
|
}
|
|
|
|
private void TryPickup()
|
|
{
|
|
Collider[] hits = Physics.OverlapSphere(PlayerTransform.position, PickupDistance);
|
|
|
|
foreach (Collider hit in hits)
|
|
{
|
|
if (hit.transform == transform) {
|
|
Pickup();
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
private void Pickup()
|
|
{
|
|
isHeld = true;
|
|
m_rigidbody.isKinematic = true;
|
|
transform.SetParent(HandTransform);
|
|
transform.localPosition = Vector3.zero;
|
|
transform.localRotation = Quaternion.identity;
|
|
}
|
|
|
|
private void Drop()
|
|
{
|
|
isHeld = false;
|
|
transform.SetParent(null);
|
|
m_rigidbody.isKinematic = false;
|
|
}
|
|
|
|
private void Throw()
|
|
{
|
|
if (!isHeld)
|
|
return;
|
|
|
|
Drop();
|
|
m_rigidbody.AddForce(PlayerTransform.forward * ThrowForce, ForceMode.Impulse);
|
|
}
|
|
} |