Drag and drop with 3D elements, how to deal with 3D position and 2D screen mouse position ?

Hi guys

I would like to make a system that allow a player to move a 3D element from a position to another by clicking on it, dragging it, and releasing it.

But i want aswell to check if he releases on a valid place, because the player has to release on 3D.

I don’t see how to manage such a challenge, what do you guys think about it ?

I wan’t the player to click on a 3D item, that will start the drag system, and i want to check if he drop on another 3D item, but i can’t just compare the 3D transform.position of the item, since he’s moving on a 2D screen space.

Same problem for my dragging actor, he is moving a 3D transform by moving the mouse in a 2D screen space …

Thanks for any help !

hi @NicoVlhv

You’ll be better of watching introductory tutorials first.

Also, did you google for it? I did. I tried keywords: “unity drag and drop tutorial 3d objects”

I get really nice results, even with thumbnail images.

Your explanation doesn’t detail how you want to handle item holding phase:
Is the item a symbol during drag?
Or is the item some concrete item in front of viewer?
Is this for 2D, 3rd person or 1st person?

But anyway - here are some things / steps you might use

  • Implement (UI) event system events, begin drag, end drag - check the manual for what you need
  • Raycasting - on end drag, Raycast to world from screen point / pointer location
  • Put your “ok” to drop elements in certain layer
  • Check that collider you hit, is in that layer (floor perhaps?)
  • Get the ray hit point
  • Spawn your item to that point, plus offset it by object bounds, depending on pivot, or maybe drop item from above, whatever is needed

Hi ! Thanks for your answer.
Sorry for the lack of information i provided, i’ll try with your advices.

What i want to do, is moving a 3D item to another 3D item location by a drag&drop system, so my 3D item can swap positions.

Something like : Click on item1, holding on the click while moving the mouse to item2, releasing mouse on item2 → item1 and item2 swap positions

And i want, the item to follow the mouse while dragging.

I feel like i should have explained things like that in the first way.

If anyone else has any other advices, i’ll listen carefully, thanks for sharing !

Normally you just do a raycast into the game world from the screen position. The Camera class has a bunch of useful methods.

Ok guys i’v made it ! Thanks !

My solution was to give event system component to my item.
One for pointer down, which enable a boolean, one for pointer up which disabled the boolean
And one “void update()” method that take care of moving my item3D by mouse position, and check if the boolean is true

Good luck for the next people reading this thread !

PS : i don’t know how to rename the topic with “SOLVED”