Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

Raycasting not working properly

Discussion in 'Scripting' started by Mohamed-Moustafa, Nov 16, 2019.

  1. Mohamed-Moustafa

    Mohamed-Moustafa

    Joined:
    Sep 22, 2019
    Posts:
    13
    I am new to games programming.
    I want to cast a ray down from an object that will only detect colliders in the third layer (Background, Default, Player, Foreground).

    I am using this script:

    Code (CSharp):
    1.  
    2. Vector2 raydown = transform.TransformDirection(-Vector3.up);
    3. int layerMask = 1<<3;
    4. if (Physics.Raycast(transform.position, raydown, 10, layerMask)){
    5.       Debug.Log("There is something in front of the object!");
    6.       pm.EndLevel();
    7.   }
    But for some reason, the if condition is never true.
     
  2. Emolk

    Emolk

    Joined:
    Feb 11, 2014
    Posts:
    241
    Is your game in 2D? If so, you need to use a 2D raycast.

    Try the below code:

    Code (CSharp):
    1.  
    2. Vector2 raydown = -transform.up;
    3. int layerMask = 1<<3;
    4. if (Physics.Raycast2D(transform.position, raydown, 10, layerMask)){
    5.       Debug.Log("There is something in front of the object!");
    6.       pm.EndLevel();
    7.   }
    Also you can set a LayerMask as a variable in a class, then select the layers from the inspector which is much easier to use.
     
  3. Mohamed-Moustafa

    Mohamed-Moustafa

    Joined:
    Sep 22, 2019
    Posts:
    13
    tried it, doesnt work properly. If I dont use layer mask it works fine tho. I have 4 layers (background,default,player,foreground), is using 1<<3 to select "player" layer incorrect?
     
  4. Emolk

    Emolk

    Joined:
    Feb 11, 2014
    Posts:
    241
    What are you trying to achieve with your code? From your debug statement i'm assuming you're trying to see if there are objects in front of an object? If so, you need to set your layermask to whatever you are attempting to hit with the ray. So if you want to check for objects in the foreground, you set the layermask to the foreground. If you set the layermask to the player layer, the ray will only hit objects in the player layer (ie the player).

    Go to your scene, on the top right click 'Layers'. This will show you what number you should put for your layer. Layers start at 0 so i assume player would be layer 2.
     
  5. Mohamed-Moustafa

    Mohamed-Moustafa

    Joined:
    Sep 22, 2019
    Posts:
    13
    Managed to get it to work. It was a mix between me confusing layers with sorting layers and not using Physics2D.queriesStartInColliders = false; .