Search code examples
unity-game-enginemeshmultipleselectioncollider

Unity3D : how can I dynamically create a 3D mesh with a collider based on mouse input?


Context : I am making a 3D RTS game and would like to detect the units the user is selecting by drag select ( the same way you select multiple icons on your computer desktop )

To do so, I would like to create a 3D mesh using the mouse's initial position when the user clicked and the mouses current position. A collision with the mesh would indicate that the unit is now in the selection box

How can I get the 8 points needed to create my 3D mesh ? I know the clipping planes of the camera are a good start but I do not know how to get those values.

How can I update the mesh shape and collider in a way that would not cause a massive fps drop ?


Solution

  • If you drag with mouse, you will not need a complex mesh. Use a cuboid primitive with a matching collider and then use the scaling of the object to give it the right dimensions you need. This will be very fast. A neat solution would also be to rotate that cuboid to the same angle as the camera. It might make sense to make your selection object a child of the camera objects so it moves with it. Then you only need a bit of math to transform the mouse coordinates on screen or window into the desired dimensions of the rectangle. Effectively you'll have a rectangular beam projected by the camera onto the world that way.