- Home /
Drag Objects with mouse?
Hi,
I want to drag Objects with my mouse and I made this allready:
using UnityEngine;
public class DragAndDropRaycast : MonoBehaviour {
Collider SelectedCollider;
void Update () {
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit Hit;
if (Physics.Raycast(ray, out Hit, Mathf.Infinity))
{
if (Hit.collider.tag == "selectable")
{
SelectedCollider = Hit.collider;
}
}
}
if (Input.GetMouseButton(0))
{
SelectedCollider.transform.position = ??? //What comes here?
}
}
}
I don't know what to add there... I tried so much now. Please keep it simple.
Thanks,
Jonas
Answer by Johnny_077 · Jun 16, 2019 at 02:17 PM
I found a solution :D
After geting the collider with
SelectedCollider = Hit.collider;
I move the collider with:
SelectedCollider.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 9f)); //IMPORTANT: the 9 is the Y axis in the world
I hope I can help someone else :D
Answer by talyh · Jun 16, 2019 at 01:02 AM
Really old, but really useful tutorial. https://youtu.be/c47QYgsJrWc
Yeah it looks useful, but it's for UI and I need it for 3D objects in my game world :/
Your answer
![](https://koobas.hobune.stream/wayback/20220612203252im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Dragging movement Speed 1 Answer
Move a cube with mouse relative to the camera rotation 0 Answers
OnMouseUp() Click Display Effect. 1 Answer
Instantiate and Scale with Mouse Click. 1 Answer
How to properly set the position clicked by the mouse? 0 Answers