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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Need raycasting help, ray goes above mouse position.

Discussion in '2D' started by football928, Apr 8, 2018.

  1. football928

    football928

    Joined:
    Sep 24, 2015
    Posts:
    17
    So what I'm trying to do is use a 2d raycast to detect what my mouse clicks on with 2d raycast. But when I would click the hit.collider.gameobject would return the object if I click on it. The problem is that it also hits it if you click next to it but not directly on it. Not good. I changed the collider size to smaller than the object and it started to work but still not fully working. I tried debugging with debug.drawray()... Turns out the ray is casting out maybe a meter above my click?

    Code (CSharp):
    1. if (Input.GetMouseButtonDown(0)) {
    2.            
    3.             Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    4.             mousePos.z = 100f;
    5.             RaycastHit2D hit = Physics2D.Raycast(this.transform.position, mousePos);
    6.             print (hit.collider.gameObject.name);
    7.  
    8.             Debug.DrawRay (this.transform.position, mousePos, Color.cyan, 10.0f);
    9.    if (hit.collider != null) {
    10.         //Code
    11.    }
    12.  
    13. }
    My mousepos.z is set to 100 so that the debug ray goes far enough.
     
  2. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    I think, you are taking the position of gameobject (this.transform.position) with the script as origin point for raycast. Try with mousePos (and the change mousePos.z to 100 can be wrong too, or you will do raycasting from the back).

    try something like this: RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector3.forward, 100f);
     
  3. football928

    football928

    Joined:
    Sep 24, 2015
    Posts:
    17
    Thank you so much, it is working perfectly. My original thinking when I was writing the code was you take the camera position and raycast towards the mouse position.