Search Unity

raycasting from screen for selection not working

Discussion in 'Physics' started by MoleratDigital, Jul 10, 2020.

  1. MoleratDigital

    MoleratDigital

    Joined:
    Oct 10, 2018
    Posts:
    3
    Long time lurker. First time poster. I'm trying to make my game respond differently depending on whether the player clicks on the environment or an npc/interactable object.

    I'm running into an error that has me very confused. It works perfectly when I click on the green keycard in my scene but when I click on an NPC it rarely works. I have tried changing the NPC's layer and collision object. The NPC script and the item script are both subclasses of interactable. Here's my code:

    Code (CSharp):
    1.             if (Input.GetMouseButtonDown(0) && equippedWeaponAbility != null) //TODO: make on drag method for automatic weapons
    2.             {
    3.  
    4.  
    5.                 RaycastHit hit;
    6.                 Ray ray = playerControllerCamera.ScreenPointToRay(Input.mousePosition);
    7.  
    8.                 if (Physics.Raycast(ray, out hit))
    9.                 {
    10.                     Debug.Log("[PlayerInputListener] hit object: " + hit.collider.gameObject);
    11.                     Interactable hitInteractable = hit.collider.gameObject.GetComponent<Interactable>();
    12.                     if (hitInteractable!=null)
    13.                     {
    14.                      
    15.                         equippedWeaponAbility.TriggerAbility(this, hitInteractable);
    16.                         Debug.Log("[PlayerInputListener] hit interactable: " + hit.collider.gameObject);
    17.                     }
    18.                     else
    19.                     {
    20.                         equippedWeaponAbility.TriggerAbility(this, hit.point);
    21.                         Debug.Log("[PlayerInputListener] hit non-interactable: "+hit.collider.gameObject);
    22.                     }
    23.                  
    24.                 }
    25.  
    26.  
    27.             }
    The layers are set so everything collides and I tried changing the NPC's layer so I do not think that is the issue. Initially I had capsule colliders on my NPCs but I switched to boxes to match the key item. Still no luck.

    When I click the NPC it almost always hits Cube.012 which is the floor. I have also tried removing the background so everyone is just on a plane and I get the same result.

    Any help would be greatly appreciated. Thanks!
     

    Attached Files: