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

Mouse click as Vector3 (direction from camera)

Discussion in 'Editor & General Support' started by Kamil9132, Jun 5, 2015.

  1. Kamil9132

    Kamil9132

    Joined:
    May 8, 2015
    Posts:
    7
    Hey.
    How can I get direction of mouse click?
    I want to change color of clicked cube, to determine which cube was clicked I need to find X and Z values of Vector3 at Y equal to height of cube.
    I think the best way to make it is get camera rotation and click position and create from them mouse click direction Vector3, but i don't have idea how to do it with perspective camera.
     

    Attached Files:

  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    Code (CSharp):
    1. Vector3 mousePos = Input.mousePosition;
    2. // Make sure "myCamera" is the camera that's looking at the object you want to click
    3. Ray mouseRay = myCamera.ScreenPointToRay (mousePos);
    4. RaycastHit[] objectsUnderMouse = Physics.RaycastAll (mouseRay);
    5.  
    6. foreach (RaycastHit hit in objectsUnderMouse)
    7. {
    8.     GameObject objectUnderMouse = hit.collider.gameObject;
    9.  
    10.     // Make sure the game object is the one you want, through GetComponent(), tags, layers, name, etc.
    11.     // Then do what you'd like to it.
    12. }
    Let me know if you'd like me to explain any of that to you. Also keep in mind the objects you are clicking must have a collider.
     
    Kamil9132 likes this.
  3. greg-harding

    greg-harding

    Joined:
    Apr 11, 2013
    Posts:
    519
    Kamil9132 and MSplitz-PsychoK like this.
  4. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    great minds think alike ;)
     
  5. Kamil9132

    Kamil9132

    Joined:
    May 8, 2015
    Posts:
    7
    Thank you for help!