campfire/Assets/Scripts/ItemGrabber.cs

87 lines
3.4 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ItemGrabber : MonoBehaviour {
public Transform CameraTransform;
public Transform HandTransform;
public Transform TorchHandTransform;
public CanvasGroup PrimaryIndicator;
public Text PrimaryText;
public CanvasGroup SecondaryIndicator;
public Text SecondaryText;
public LayerMask ItemLayer;
public LayerMask DroppingRaycastMask;
public float Distance;
public float ThrowVelocity;
[Header("Prefabs")]
public GameObject TorchPrefab;
[Header("Runtime values")]
public Item GrabbedItem;
public Torch Torch;
private void Start() {
PrimaryIndicator.alpha = 0;
SecondaryIndicator.alpha = 0;
}
private void Update() {
Item Item = null;
Campfire Campfire = null;
RaycastHit Hit;
Vector3 From = CameraTransform.position;
Vector3 Direction = CameraTransform.forward;
if (GrabbedItem == null) {
Debug.DrawLine(From, From + Direction * Distance, Color.red);
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 (Physics.Raycast(From, Direction, out Hit, Distance * 2f, 1 << LayerMask.NameToLayer("Campfire")) &&
Hit.collider.attachedRigidbody != null) {
Campfire = Hit.collider.attachedRigidbody.GetComponent<Campfire>();
}
if (Campfire != null && Torch == null && Input.GetButtonDown("Ignite")) {
GameObject TorchObj = Instantiate(TorchPrefab, GrabbedItem.transform.position, GrabbedItem.transform.rotation, TorchHandTransform);
Torch = TorchObj.GetComponent<Torch>();
Destroy(GrabbedItem.gameObject);
GrabbedItem = null;
} else if (Input.GetButtonDown("Grab")) {
Vector3 DropPosition;
if (Campfire != null) {
DropPosition = Campfire.transform.position + Vector3.up * 0.7f;
} else {
if (Physics.Raycast(From, Direction, out Hit, Distance * 2f, DroppingRaycastMask)) {
DropPosition = Hit.point + Hit.normal * 0.1f;
} else {
DropPosition = From + Direction * Distance;
}
}
GrabbedItem.Drop(DropPosition);
GrabbedItem = null;
}
}
PrimaryIndicator.alpha = Mathf.Lerp(PrimaryIndicator.alpha, Item != null || Campfire != null ? 1 : 0, 10f * Time.deltaTime);
if (Campfire != null && GrabbedItem != null) {
PrimaryText.text = $"Burn {GrabbedItem.name.ToLower()}";
} else if (Item != null) {
PrimaryText.text = $"Take {Item.name.ToLower()}";
}
SecondaryIndicator.alpha = Mathf.Lerp(SecondaryIndicator.alpha, Campfire != null && GrabbedItem != null && Torch == null ? 1 : 0, 10f * Time.deltaTime);
if (GrabbedItem != null) {
SecondaryText.text = $"Ignite {GrabbedItem.name.ToLower()}";
}
}
}