Nhặt và Ném đồ vật (Rigidbody)
C# Code
using UnityEngine;
public class PickupAndThrow : MonoBehaviour
{
public Transform holdPoint; // Điểm giữ vật thể trước mặt camera/player
public float throwForce = 20f;
private GameObject heldObject;
private Rigidbody heldObjectRb;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (heldObject == null)
{
// Thử nhặt vật thể
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, 5f))
{
if (hit.collider.GetComponent<Rigidbody>()) // Kiểm tra có Rigidbody không
{
PickupObject(hit.collider.gameObject);
}
}
}
else
{
// Thả vật thể
DropObject();
}
}
if (heldObject != null && Input.GetMouseButtonDown(0)) // Nút chuột trái để ném
{
ThrowObject();
}
}
void PickupObject(GameObject obj)
{
heldObject = obj;
heldObjectRb = obj.GetComponent<Rigidbody>();
heldObjectRb.useGravity = false;
heldObjectRb.drag = 10;
heldObjectRb.constraints = RigidbodyConstraints.FreezeRotation;
heldObject.transform.parent = holdPoint;
heldObject.transform.position = holdPoint.position;
}
void DropObject()
{
heldObjectRb.useGravity = true;
heldObjectRb.drag = 1;
heldObjectRb.constraints = RigidbodyConstraints.None;
heldObject.transform.parent = null;
heldObject = null;
}
void ThrowObject()
{
Rigidbody rbToThrow = heldObjectRb;
DropObject(); // Thả ra trước khi ném
rbToThrow.AddForce(transform.forward * throwForce, ForceMode.Impulse);
}
}Cho phép người chơi nhặt các vật thể có Rigidbody, giữ chúng trước mặt và ném đi bằng một lực.