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

Issue with Raycast2D

Discussion in '2D' started by RzRsEdge, Sep 11, 2015.

  1. RzRsEdge

    RzRsEdge

    Joined:
    Oct 27, 2013
    Posts:
    14
    Trying to detect if the mouse has passed over two colliders is not working unless the mouse is moved slowly. If the mouse is moved at speed, only the first collision is detected.

    Any ideas?


    Code (CSharp):
    1. if (Input.GetMouseButton(0))
    2.  
    3. {
    4.  
    5. RaycastHit2D hit = Physics2D.Raycast(mainCamera.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
    6.  
    7. if (hit)
    8. {
    9.     if (hit.collider.tag == "validTag")
    10.     {
    11.         if (firstCollider = null)
    12.         {
    13.             Debug.Log("Hit First Collider");
    14.             firstCollider = hit.collider;
    15.         }
    16.         else
    17.         {
    18.             if (hit.collider != firstCollider)
    19.             {
    20.                 Debug.Log("Hit Second");i
    21.             }
    22.         }
    23.     }
    24. }
    25.  
    26. }
     
    Last edited: Sep 12, 2015
  2. Rostam24

    Rostam24

    Joined:
    Mar 5, 2014
    Posts:
    119
    Where did you place that code? In FixedUpdate? If so, try putting it in Update.

    And a possible workaround would be to store the previous mouse position, then on mousebutton down raycast between the last position and the new position.
     
    RzRsEdge likes this.
  3. RzRsEdge

    RzRsEdge

    Joined:
    Oct 27, 2013
    Posts:
    14
    No, that was in Update.

    Raycasting between the current and previous positions to detect a collision is a good idea, I'll give that a try.
     
  4. RzRsEdge

    RzRsEdge

    Joined:
    Oct 27, 2013
    Posts:
    14
    Brilliant mate, that sorted it. Thanks for the help.