- Home /
How to move a child object by drag and drop? Please help me :(
Hey guys, so i have an object on a plane and i want to move it on the x and z axis by using drag and drop with my mouse. I converted x,y to x,z by rotating the vector3. But i want the object to be a child of an empty object, so i can use the empty one as a kind of folder to store all object inside. The problem is i can access the objects with the OnMouseDrag function, or i made a mistake. Can someone check my code and help me pls :) Thanks in advance
Regards,
Here is my code:
public class DragAndDrop : Interactable {
Vector3 lastPosition;
Vector3 currentPosition;
Interactable interactable;
Ray ray;
RaycastHit hit;
void Update() {
FindObject ();
MoveSelectedObject ();
}
void FindObject() {
if (Input.GetMouseButtonDown (0)) {
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit)) {
interactable = hit.collider.GetComponent<Interactable> ();
if (interactable != null) {
Debug.Log ("Hit! Interactable: " + hit.collider.name + hit.collider.transform.localPosition);
lastPosition = Camera.main.WorldToScreenPoint (hit.collider.transform.localPosition);
}
}
}
}
void OnMouseDown() {
}
void MoveSelectedObject() {
if (interactable != null && Input.GetMouseButtonDown (0)) {
currentPosition = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, lastPosition.z));
currentPosition = Quaternion.Euler (90, 0, 0) * currentPosition;
currentPosition.y = 0;
currentPosition.x = Mathf.Round (currentPosition.x);
currentPosition.z = Mathf.Round (currentPosition.z);
hit.collider.transform.localPosition = currentPosition;
}
}
}
Your answer
Follow this Question
Related Questions
Stop the lasers from keep bouncing 1 Answer
How to place an object in the direction of a raycast 1 Answer
Not getting right value; ScreenPointToRay 0 Answers
Using raycast - Why can't I get a variable on the object I hit? 1 Answer
Move CharacterController a specified distance away from starting position. 1 Answer