I consulted search engine after search engine, forum after forum. I just can’t find a suitable answer to this question!
Is there a script that I can use, which allows the player to drag a rigidbody when it is clicked and dragged? I need this for a game, which you need to drag objects to create a bridge, allowing gravity to rotate it naturally. I don’t need to rotate it, just be able to drag it. Thanks in advance!
2 Answers
2
This was answered here:
http://forum.unity3d.com/threads/56460-Drag-Rigidbody-script-works-but-passes-through-collider
If DragRigidBody doesn’t work for what you need, try using Erich5h5’s DragObject script:
http://wiki.unity3d.com/index.php?title=DragObject
I’m actually going to attempt this myself now.
Here, i wrote a very simple script for dragging any Object with the rigidbody component.
I hope i could help you.
using UnityEngine;
using System.Collections;
public class DragRigidbody : MonoBehaviour
{
public float catchingDistance = 3f;
bool isDragging = false;
GameObject draggingObject;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(0))
{
if (!isDragging)
{
draggingObject = GetObjectFromMouseRaycast();
if (draggingObject)
{
draggingObject.GetComponent<Rigidbody>().isKinematic = true;
isDragging = true;
}
}
else if (draggingObject != null)
{
draggingObject.GetComponent<Rigidbody>().MovePosition(CalculateMouse3DVector());
}
}
else {
if (draggingObject != null)
{
draggingObject.GetComponent<Rigidbody>().isKinematic = false;
}
isDragging = false;
}
}
private GameObject GetObjectFromMouseRaycast()
{
GameObject gmObj = null;
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit)
{
if (hitInfo.collider.gameObject.GetComponent<Rigidbody>() &&
Vector3.Distance(hitInfo.collider.gameObject.transform.position,
transform.position) <= catchingDistance)
{
gmObj = hitInfo.collider.gameObject;
}
}
return gmObj;
}
private Vector3 CalculateMouse3DVector()
{
Vector3 v3 = Input.mousePosition;
v3.z = catchingDistance;
v3 = Camera.main.ScreenToWorldPoint(v3);
Debug.Log(v3); //Current Position of mouse in world space
return v3;
}
}
From looking at your profile, none of your 15 questions have selected answers. Either none of them have good answers or you are forgetting to select them. If any of them have decent answers, please remember to select them.
– SpinnernicholasHave you tried the DragRigidbody.js script that comes with Unity? You can get it by Assets > Import Package > Scripts. If you've tried it, how is the behavior you want different from this scripts behavior?
– robertbu