I have a pickup script to pick up, throw, and drop rigid bodies, the problem I’m having is that when dropping an object while moving it quickly it doesn’t preserve its velocity and just drops to the floor, I am unsure about how to achieve what I’m looking for and clear help would be appreciated.
Here’s the pick up script in question.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUp : MonoBehaviour
{
public float pickUpRange = 5;
public Transform holdParent;
private GameObject heldObject;
public float moveForce = 250f;
public float Thrust = 2f;
public Transform target;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (heldObject == null)
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, pickUpRange))
{
PickUpObject(hit.transform.gameObject);
}
}
else
{
DropObject();
}
}
if (heldObject != null)
{
MoveObject();
}
if (Input.GetMouseButtonDown(0))
{
ThrowObject();
}
}
void MoveObject()
{
if (Vector3.Distance(heldObject.transform.position, holdParent.position) > 0.1f)
{
Vector3 moveDirection = (holdParent.position - heldObject.transform.position);
heldObject.GetComponent<Rigidbody>().AddForce(moveDirection * moveForce);
}
}
void PickUpObject(GameObject pickObject)
{
if (pickObject.GetComponent<Rigidbody>())
{
Rigidbody Rigid = pickObject.GetComponent<Rigidbody>();
//Rigid.constraints = RigidbodyConstraints.FreezeRotation;
Rigidbody objectRig = pickObject.GetComponent<Rigidbody>();
objectRig.useGravity = false;
objectRig.drag = 10;
objectRig.transform.parent = holdParent;
heldObject = pickObject;
}
}
void DropObject()
{
Rigidbody Rigid = heldObject.GetComponent<Rigidbody>();
Rigid.constraints = RigidbodyConstraints.None;
Rigid.freezeRotation = false;
Rigidbody heldRig = heldObject.GetComponent<Rigidbody>();
heldRig.useGravity = true;
heldRig.drag = 1f;
heldObject.transform.parent = null;
heldObject = null;
}
void ThrowObject()
{
Rigidbody Rigid = heldObject.GetComponent<Rigidbody>();
Rigid.constraints = RigidbodyConstraints.None;
Rigid.AddForce(transform.forward * Thrust);
Rigid.freezeRotation = false;
Rigidbody heldRig = heldObject.GetComponent<Rigidbody>();
heldRig.useGravity = true;
heldRig.drag = 1f;
heldObject.transform.parent = null;
heldObject = null;
}
}