62 lines
		
	
	
		
			2.1 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			62 lines
		
	
	
		
			2.1 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 CanvasGroup GrabHint;
 | |
|     public Text GrabText;
 | |
|     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.");
 | |
|         }
 | |
|         if (GrabText == null) {
 | |
|             Debug.LogWarning("Player's GrabText is not set, and pick up texts will not necessarily match the object.");
 | |
|         }
 | |
|     }
 | |
| 
 | |
|     private void Update() {
 | |
|         Item Item = 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 (Input.GetButtonDown("Grab")) {
 | |
|             Vector3 DropPosition;
 | |
|             if (Physics.Raycast(From, Direction, out Hit, Distance * 2f)) {
 | |
|                 DropPosition = Hit.point + Hit.normal * 0.1f;
 | |
|             } else {
 | |
|                 DropPosition = From + Direction * Distance;
 | |
|             }
 | |
|             GrabbedItem.Drop(DropPosition);
 | |
|             GrabbedItem = null;
 | |
|         }
 | |
| 
 | |
|         if (GrabHint != null) {
 | |
|             GrabHint.alpha = Mathf.Lerp(GrabHint.alpha, Item != null ? 1 : 0, 10f * Time.deltaTime);
 | |
|         }
 | |
|         if (Item != null && GrabText != null) {
 | |
|             GrabText.text = $"Take {Item.name}";
 | |
|         }
 | |
|     }
 | |
| }
 |