2020-04-18 22:52:37 +02:00
|
|
|
|
using System.Collections;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using UnityEngine;
|
2020-04-19 00:30:27 +02:00
|
|
|
|
using UnityEngine.UI;
|
2020-04-18 22:52:37 +02:00
|
|
|
|
|
|
|
|
|
public class ItemGrabber : MonoBehaviour {
|
|
|
|
|
public Transform CameraTransform;
|
|
|
|
|
public Transform HandTransform;
|
|
|
|
|
public CanvasGroup GrabHint;
|
2020-04-19 00:30:27 +02:00
|
|
|
|
public Text GrabText;
|
2020-04-18 22:52:37 +02:00
|
|
|
|
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.");
|
|
|
|
|
}
|
2020-04-19 00:30:27 +02:00
|
|
|
|
if (GrabText == null) {
|
|
|
|
|
Debug.LogWarning("Player's GrabText is not set, and pick up texts will not necessarily match the object.");
|
|
|
|
|
}
|
2020-04-18 22:52:37 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void Update() {
|
|
|
|
|
Item Item = null;
|
|
|
|
|
RaycastHit Hit;
|
|
|
|
|
Vector3 From = CameraTransform.position;
|
|
|
|
|
Vector3 Direction = CameraTransform.forward;
|
|
|
|
|
if (GrabbedItem == null) {
|
2020-04-19 00:30:27 +02:00
|
|
|
|
Debug.DrawLine(From, From + Direction * Distance, Color.red);
|
2020-04-18 22:52:37 +02:00
|
|
|
|
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")) {
|
2020-04-19 00:30:27 +02:00
|
|
|
|
Vector3 DropPosition;
|
|
|
|
|
if (Physics.Raycast(From, Direction, out Hit, Distance * 2f)) {
|
|
|
|
|
DropPosition = Hit.point + Hit.normal * 0.1f;
|
|
|
|
|
} else {
|
|
|
|
|
DropPosition = From + Direction * Distance;
|
2020-04-18 22:52:37 +02:00
|
|
|
|
}
|
2020-04-19 00:30:27 +02:00
|
|
|
|
GrabbedItem.Drop(DropPosition);
|
2020-04-18 22:52:37 +02:00
|
|
|
|
GrabbedItem = null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (GrabHint != null) {
|
|
|
|
|
GrabHint.alpha = Mathf.Lerp(GrabHint.alpha, Item != null ? 1 : 0, 10f * Time.deltaTime);
|
|
|
|
|
}
|
2020-04-19 00:30:27 +02:00
|
|
|
|
if (Item != null && GrabText != null) {
|
|
|
|
|
GrabText.text = $"Take {Item.name}";
|
|
|
|
|
}
|
2020-04-18 22:52:37 +02:00
|
|
|
|
}
|
|
|
|
|
}
|