Search Unity

Physics2D.Raycast not working

Discussion in '2D' started by pesek23, Feb 7, 2016.

  1. pesek23

    pesek23

    Joined:
    Feb 3, 2016
    Posts:
    5
    Hello there.

    I'm trying to use Physics2D.Raycast to check if user hit the game object. I try to use code i found in the forum:

    void Update()
    {
    if ( Input.GetMouseButtonDown( 0 ) )
    {
    Vector2 worldPoint = Camera.main.ScreenToWorldPoint( Input.mousePosition );
    RaycastHit2D hit = Physics2D.Raycast( worldPoint, Vector2.zero );
    if ( hit.collider != null )
    {
    Debug.Log( hit.collider.name );
    }
    }
    }

    So i create new Game object of type Sprite (2D object), add C# with code above. But hits not working. It works only if i add "Box collider 2D" to the game object.

    I'm not sure if i there must be Box collider or not, becouse in every example there is not any collider used.

    Sorry for question but I'm newbie in unity and i'm stuck in this for whole weekend.

    Thank you.
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,459
    Physics2D is a physics API and works with physics objects. GameObject is just a container of components, it doesn't have any spatial dimensions on its own.

    Physics2D.Raycast checks if the ray intersects any 2D colliders as the documentation states.

    Your own code uses 'if ( hit.collider != null )' which is saying if it hit a 'collider' so that's a hint. :)
     
  3. pesek23

    pesek23

    Joined:
    Feb 3, 2016
    Posts:
    5
    Ok, thank you.