- Home /
How to drag / pick up objects with Mouse.
How to drag / pick up objects with Mouse.
Im looking how to be able to grab and swing, drag or what ever -ANYWHERE on the screen with the click and hold of the mouse button,
this script I have should be accurate but its not working THIS IS A 2D GAME JAVSCRIPT
Please help and post corrected script
Keep in mind= -It Must be able to be dragged anywhere on screen
-On mouse hold button down
-upon release just lets go of object
var spring = 50.0;
var damper = 5.0;
var drag = 10.0;
var angularDrag = 5.0;
5. var distance = 0.2;
var attachToCenterOfMass = false;
private var springJoint : SpringJoint;
10. function Update ()
{
// Make sure the user pressed the mouse down
if (!Input.GetMouseButtonDown (0))
return;
15.
var mainCamera = FindCamera();
// We need to actually hit an object
var hit : RaycastHit;
20. if (!Physics.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition), hit, 100))
return;
// We need to hit a rigidbody that is not kinematic
if (!hit.rigidbody2D || hit.rigidbody2D.isKinematic)
return;
25.
if (!springJoint)
{
var go = new GameObject("Rigidbody dragger");
var body : Rigidbody2D = go.AddComponent ("Rigidbody2D") as Rigidbody2D;
30. springJoint = go.AddComponent ("SpringJoint");
body.isKinematic = true;
}
springJoint.transform.position = hit.point;
35. if (attachToCenterOfMass)
{
var anchor = transform.TransformDirection(hit.rigidbody.centerOfMass) + hit.rigidbody2D.transform.position;
anchor = springJoint.transform.InverseTransformPoint(anchor);
springJoint.anchor = anchor;
40. }
else
{
springJoint.anchor = Vector3.zero;
}
45.
springJoint.spring = spring;
springJoint.damper = damper;
springJoint.maxDistance = distance;
springJoint.connectedBody = hit.rigidbody;
50.
StartCoroutine ("DragObject", hit.distance);
}
function DragObject (distance : float)
55. {
var oldDrag = springJoint.connectedBody.drag;
var oldAngularDrag = springJoint.connectedBody.angularDrag;
springJoint.connectedBody.drag = drag;
springJoint.connectedBody.angularDrag = angularDrag;
60. var mainCamera = FindCamera();
while (Input.GetMouseButton (0))
{
var ray = mainCamera.ScreenPointToRay (Input.mousePosition);
springJoint.transform.position = ray.GetPoint(distance);
65. yield;
}
if (springJoint.connectedBody)
{
springJoint.connectedBody.drag = oldDrag;
70. springJoint.connectedBody.angularDrag = oldAngularDrag;
springJoint.connectedBody = null;
}
}
75. function FindCamera ()
{
if (GetComponent.<Camera>())
return GetComponent.<Camera>();
else
80. return Camera.main;
}
Your answer

Follow this Question
Related Questions
Accessing components via script and assigning randomized values to their parameters? 1 Answer
Use vim with unity? 1 Answer
Can you trick a Ui Button that it is being clicked with code? 3 Answers
difference between Gameobject.findobjectoftype<...>(); and simple findobjectoftype<...>(); ? 2 Answers
Axis disabled? (IO have not changed default input except fire1 and fire2) ? 0 Answers