Hi.
I ran into a few problems with Unity’s DragRigidbody script. First off, I would like the object being dragged to move faster, I’d like the object to always move as the player moves, and to rotate with the player, so it is always in the view.
Here is my modified DragRigidbody script that I’d like to add these features to:
var damper = 5.0;
var drag = 10.0;
var angularDrag = 5.0;
var distance = 0.2;
var throwForce = 5.5;
var attachToCenterOfMass = false;
var isPressed = false;
static var springJoint : SpringJoint;
function Update ()
{
// Make sure the user pressed the mouse down
if (!Input.GetButtonDown ("Fire1"))
return;
if (Input.GetButtonDown ("Fire1")) {
isPressed = true;
Debug.Log("isPressed = true;");
}
var mainCamera = FindCamera();
// We need to actually hit an object
var hit : RaycastHit;
if (!Physics.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition), hit, Mathf.Infinity))
return;
// We need to hit a rigidbody that is not kinematic
if (!hit.rigidbody || hit.rigidbody.isKinematic)
return;
if (!springJoint)
{
var go = new GameObject("Rigidbody dragger");
var body : Rigidbody = go.AddComponent ("Rigidbody") as Rigidbody;
springJoint = go.AddComponent ("SpringJoint");
body.isKinematic = true;
}
springJoint.transform.position = hit.point;
if (attachToCenterOfMass)
{
var anchor = transform.TransformDirection(hit.rigidbody.centerOfMass) + hit.rigidbody.transform.position;
anchor = springJoint.transform.InverseTransformPoint(anchor);
springJoint.anchor = anchor;
}
else
{
springJoint.anchor = Vector3.zero;
}
springJoint.spring = spring;
springJoint.damper = damper;
springJoint.maxDistance = distance;
springJoint.connectedBody = hit.rigidbody;
StartCoroutine ("DragObject", hit.distance);
}
function DragObject (distance : float)
{
var oldDrag = springJoint.connectedBody.drag;
var oldAngularDrag = springJoint.connectedBody.angularDrag;
springJoint.connectedBody.drag = drag;
springJoint.connectedBody.angularDrag = angularDrag;
var mainCamera = FindCamera();
while (isPressed) //(Input.GetButton ("Fire1"))
{
var ray = mainCamera.ScreenPointToRay (Input.mousePosition);
springJoint.transform.position = ray.GetPoint(distance);
yield;
while (Input.GetButtonDown("Fire2")) {
springJoint.rigidbody.MovePosition(transform.position + transform.forward * throwForce);
yield WaitForSeconds(0.01);
isPressed = false;
Debug.Log("Thrown? DragRigidbody.js");
}
}
if (springJoint.connectedBody)
{
springJoint.connectedBody.drag = oldDrag;
springJoint.connectedBody.angularDrag = oldAngularDrag;
springJoint.connectedBody = null;
}
}
function FindCamera ()
{
if (camera)
return camera;
else
return Camera.main;
}
If you could help me, I would greatly appreciate it!
Thanks!