Search Unity

How to instantiate an object at mouse position thanks in advance

Discussion in 'Scripting' started by Benjamin6817, Nov 25, 2012.

  1. Benjamin6817

    Benjamin6817

    Joined:
    Aug 17, 2012
    Posts:
    4
    Hello all!

    So, I've been working on my project and development has been pretty steady, until one of our artist thought a level design system of sorts would be great. I, being one of the programmers need to make it, but constructing the mechanics have been severely painful, and I have painstakingly managed to pull out some working, but buggy code. I wanted to know what the easiest way to instantiate an object at the mouse position would be... After hours of Google searches, I can't find anything of much use. My old method used raycasts, I would make the ray variable set to the mouses position by passing it through a world space conversion. i.e.:
    Code (csharp):
    1. Ray ray = Camera.main.ViewportPointToRay(Input.mousePosition)
    It worked, but not well. It appeared as if the position was randomly incremented when I didn't move my mouse. Can someone tell me how I should go about this, or provide some API reference for something I can use? Thanks in advance. Also, please, if you find a solution that requires pro please do not post because our team is non-profit and cannot afford it.

    Regards,
    Ben
     
  2. Loius

    Loius

    Joined:
    Aug 16, 2012
    Posts:
    546
    Viewport seems to take a Vector3 in the range of 0>1 on x and y. If you send the command through ScreenToViewportPoint, then ViewportPointToRay, does that help?

    (If you're in the editor, I believe you should use Camera.current and Event.current.mousePosition, instead of Camera.main and Input. If not, you're good with Input and .main)
     
  3. Benjamin6817

    Benjamin6817

    Joined:
    Aug 17, 2012
    Posts:
    4
    About using Event.current.mousePosition, what seems to be the different between the two? Also, about Camera.current, if I used Camera.main and my camera is tagged MainCamera (it is by the way), then why does it matter? Thanks for all help, Loius.

    Regards,
    Ben
     
    Last edited: Nov 28, 2012