This is my script which allows the player to pick up rigid body objects with holding left click, then drop them when the button is released. (I didn’t write this myself.)
using UnityEngine;
using System.Collections;
public class CursorScript : MonoBehaviour {
float drag = 1.0f;
float angularDrag = 5.0f;
bool attachToCenterOfMass = false;
private FixedJoint fixedJoint;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void OnGui()
{
GUILayout.BeginVertical ();
if (Input.GetKeyDown (KeyCode.Escape)) {
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
void Update() {
if (!Input.GetMouseButtonDown (0))
return;
var mainCamera = FindCamera();
RaycastHit hit;
if (!Physics.Raycast(mainCamera.ScreenPointToRay(new Vector2(Screen.width / 2, Screen.height / 2)), out hit, 3))
return;
if (!hit.rigidbody || hit.rigidbody.isKinematic)
return;
if (!fixedJoint) {
GameObject go = new GameObject("Rigidbody dragger");
Rigidbody body = go.AddComponent<Rigidbody>() as Rigidbody;
fixedJoint = go.AddComponent<FixedJoint>() as FixedJoint;
body.isKinematic = true;
}
fixedJoint.transform.position = hit.point;
if (attachToCenterOfMass) {
Vector3 anchor = transform.TransformDirection(hit.rigidbody.centerOfMass) + hit.rigidbody.transform.position;
anchor = fixedJoint.transform.InverseTransformPoint(anchor);
fixedJoint.anchor = anchor;
} else {
fixedJoint.anchor = Vector3.zero;
}
fixedJoint.connectedBody = hit.rigidbody;
StartCoroutine("DragObject", hit.distance);
}
IEnumerator DragObject (float distance) {
float oldDrag = fixedJoint.connectedBody.drag;
float oldAngularDrag = fixedJoint.connectedBody.angularDrag;
fixedJoint.connectedBody.drag = drag;
fixedJoint.connectedBody.angularDrag = angularDrag;
Camera mainCamera = FindCamera();
while (Input.GetMouseButton (0)) {
var ray = mainCamera.ScreenPointToRay (new Vector2(Screen.width / 2, Screen.height / 2));
fixedJoint.transform.position = ray.GetPoint(distance);
yield return null;
}
if (fixedJoint.connectedBody) {
fixedJoint.connectedBody.drag = oldDrag;
fixedJoint.connectedBody.angularDrag = oldAngularDrag;
fixedJoint.connectedBody = null;
}
}
Camera FindCamera () {
if (GetComponent<Camera>())
return GetComponent<Camera>();
else
return Camera.main;
}
}
It works fine, but I was wondering how I could edit this so that the object is thrown instead of dropped? I’m not very good with C# so I don’t know where to begin.