campfire/Assets/Scripts/ItemGrabber.cs

52 lines
1.7 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemGrabber : MonoBehaviour {
public Transform CameraTransform;
public Transform HandTransform;
public CanvasGroup GrabHint;
public LayerMask ItemLayer;
public float Distance;
public float ThrowVelocity;
[Header("Runtime values")]
public Item GrabbedItem;
private void Awake() {
if (GrabHint == null) {
Debug.LogWarning("Player's GrabHint is not set, and pick ups will not be indicated.");
}
}
private void Update() {
Item Item = null;
RaycastHit Hit;
Vector3 From = CameraTransform.position;
Vector3 Direction = CameraTransform.forward;
if (GrabbedItem == null) {
if (Physics.Raycast(From, Direction, out Hit, Distance, ItemLayer) &&
Hit.collider.attachedRigidbody != null) {
Item = Hit.collider.attachedRigidbody.GetComponent<Item>();
}
if (Item != null && Input.GetButtonDown("Grab")) {
Item.PickUp(HandTransform);
GrabbedItem = Item;
}
} else if (Input.GetButtonDown("Grab")) {
Vector3 Forward = CameraTransform.forward;
if (Physics.Raycast(From, Direction, out Hit, 10f)) {
// Throw direction should be where we're pointign, but slightly upwards
Forward = (Hit.point - From).normalized + Vector3.up;
}
GrabbedItem.Drop(Forward * ThrowVelocity);
GrabbedItem = null;
}
if (GrabHint != null) {
GrabHint.alpha = Mathf.Lerp(GrabHint.alpha, Item != null ? 1 : 0, 10f * Time.deltaTime);
}
}
}