72 lines
2.0 KiB
C#
72 lines
2.0 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class ItemGrabber : MonoBehaviour
|
|
{
|
|
public static ItemGrabber instance;
|
|
void Awake()
|
|
{
|
|
instance = this;
|
|
}
|
|
public float pickupDistance;
|
|
public Pickable currentTarget;
|
|
public Pickable grabbingItem;
|
|
public Transform holdingPoint;
|
|
public Transform scanningItem;
|
|
public Transform arm;
|
|
void Update()
|
|
{
|
|
ScanForTarget();
|
|
CalculateHoldingPointVelocity();
|
|
|
|
arm.transform.localRotation = arm.transform.localRotation.with(x: Camera.main.transform.localRotation.x);
|
|
|
|
if (currentTarget != null && Input.GetMouseButtonDown(0))
|
|
{
|
|
currentTarget.Grab();
|
|
|
|
grabbingItem = currentTarget;
|
|
currentTarget = null;
|
|
return;
|
|
}
|
|
|
|
if (grabbingItem != null && Input.GetMouseButtonUp(0))
|
|
{
|
|
grabbingItem.LetGo(holdingPointVelocity);
|
|
grabbingItem = null;
|
|
}
|
|
}
|
|
|
|
Vector3 m_lastHoldingPointPos;
|
|
public Vector3 holdingPointVelocity;
|
|
void CalculateHoldingPointVelocity(){
|
|
holdingPointVelocity = holdingPoint.position - m_lastHoldingPointPos;
|
|
m_lastHoldingPointPos = holdingPoint.position;
|
|
}
|
|
void ScanForTarget()
|
|
{
|
|
if (grabbingItem != null) { return; }
|
|
|
|
RaycastHit hit = new RaycastHit();
|
|
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
|
|
if (Physics.Raycast(ray, out hit, pickupDistance))
|
|
{
|
|
scanningItem = hit.transform;
|
|
Pickable pick = hit.transform.GetComponent<Pickable>();
|
|
if (pick != null)
|
|
{
|
|
currentTarget = pick.isGrabbing ? null : pick;
|
|
Debug.DrawRay(transform.position, hit.point, Color.green);
|
|
|
|
}
|
|
else
|
|
{
|
|
currentTarget = null;
|
|
Debug.DrawRay(transform.position, hit.point, Color.red);
|
|
|
|
}
|
|
}
|
|
}
|
|
}
|