I have maybe a dumb question, but how do I drag a GameObject when I click the mouse?
I'd like to use OnMouseDrag. When the user clicks on my GameObject it first does some animation (moves forward a bit). When the user still holds down the mouse button and moves the mouse, I'd like to have the GameObject move with it (with dampening).
Tried some stuff out but I can't get it to work.
Does anyone know how to do this?
It would be of great help!
There is a script which comes with Standard Assets of Unity called `DragRigidbody.js`. You can play with it by following these steps:
Create an empty `Scene` with a `Terrain`
Add some `GameObject` like `Cube` and `Sphere`
Assign `Rigidbody` to the ones that you want to be able to Drag (`Component` > `Physics` > `Rigidbody`)
Add a `First Person Controller` from the Prefabs of Standard Assets
Finally drag the `DragRigidbody.js` on the `First Person Controller` object in your scene.
Press the `Play` button and you are good to go
I don't know in how much into details you want to go, but in general the `DragRigidbody.js` script is using a combination of `Raycast`, `Rigidbody` and `SpringJoint` to achieve the Drag and Drop.
You can also check the Room of Shadows example which is a little bit more complicated but this is because they also highlighting the objects and playing with lights/shadows.
the code on the previous page, it is moving the object from the angle of camera, I need the version which moves the object in respect to planes, from cameras angle [ for example from the cameras angle if i move the object it moves on the direction of y, but i want it to move on the direction of x , or z because its my plane, alltough the object moves on x, and partial y and partial z because of my camera angle how can i block it from moving on y direction and make it move on z only?
public void OnDrag (PointerEventData eventData)
{
Vector3 delta = eventData.pointerPressRaycast.worldPosition - eventData.pointerCurrentRaycast.worldPosition;
delta.z = 0; // this is to keep the camera's Z fixed, change at will
m_camera.transform.position += delta;
CheckLimits();
}
Make sure you add the IBeginDragHandler, IDragHandler, IEndDragHandler interfaces to your MonoBehaviour.