Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Get position in game world of my mouse down

Discussion in 'Scripting' started by TheCelt, Jun 1, 2016.

  1. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    724
    Hello

    I followed a tutorial to get the position in the game world of my mouse when i mouse button down, but it doesn't work. It gives a position far removed from the correct position.

    My floor position is 0,0,0 and i have a box collider with this code attatched:


    Code (CSharp):
    1. void OnMouseDown()
    2. {
    3.    Vector3 p = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    4.    Debug.Log(p);
    5. }
    The result is something far from the real location like this:

    My camera is angled if that matters like this:

    So i have an isometric viewing angle.

    How do i correct this ? Seems the tutorial i followed was wrong.
     
  2. HellSinker

    HellSinker

    Joined:
    Apr 18, 2013
    Posts:
    65
    The normal way to achieve the results is via ray casting...

    http://unity3d.com/learn/tutorials/topics/physics/raycasting should give you some ideas...

    If you have sometime I can make a quick example; though I doubt I will be first to show exactly how it is done...

    Edit: Basically you fire a ray in the direction of the camera from the mouse position... see what object it hits, you can even get texcoords and fragment information from the ray...
     
    Krish-Vikram likes this.
  3. ericbegue

    ericbegue

    Joined:
    May 31, 2013
    Posts:
    1,353
    As @HellSinker suggested, raycasting is the way to go.

    About:
    Code (CSharp):
    1. Vector3 p = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    ScreenToWorldPoint expects the z-coordinate to be provided and non zero. However Input.mousePosition.z is always zero.