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

Getting world position from screen position using Raycast.

Discussion in 'Scripting' started by Decoder46, Jul 12, 2016.

  1. Decoder46

    Decoder46

    Joined:
    Jun 12, 2015
    Posts:
    20
    Hi, I am trying to get world point by mouse position using the Raycast and it's not always working.
    It's sometimes just ignore some of the objects. I am using it to place GameObject on node but it's just past over some of the nodes. All nodes have the same collider non trigger.
    Code:
    Code (CSharp):
    1.  
    2. Ray r = Camera.main.ScreenPointToRay( Input.mousePosition);
    3. if (Physics.Raycast(r, out hit) && hit.transform.tag == "Node")
    4. {
    5.      Transform objectHit = hit.transform;
    6.       towerToPlace.transform.position = objectHit.position;
    7. }
    8. Debug.DrawRay(r.origin , r.direction * 100, Color.red, 100, true);
    The debug draw shows the expected results.
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    Try putting Mathf.Infinity as a length, because if I'm right, by default it isn't infinite
     
  3. Decoder46

    Decoder46

    Joined:
    Jun 12, 2015
    Posts:
    20
    Nope, still the same...
     
  4. Decoder46

    Decoder46

    Joined:
    Jun 12, 2015
    Posts:
    20
    I am such an idiot. the gameObject had a sphere collider so the raycast hit him first and the radius was 10 deliberately. lol
     
    CheekySparrow78 likes this.