Search Unity

I can't make a Raycast2D detect a specific layer

Discussion in '2D' started by Broly_MacBroly, Nov 23, 2022.

  1. Broly_MacBroly

    Broly_MacBroly

    Joined:
    Oct 19, 2022
    Posts:
    5
    I've been working on an enemy for a shooter plataformer 2D and so far everything has gone quite smooth, however the enemy tries to shoot you through plataforms, I tried to fix that making a code that only instantiates projectiles when the raycast is hitting a specific Layer but when I implement said code the enemy downright stops firing, what can I do to fix it?
    Code (CSharp):
    1.  void Start()
    2.     {
    3.         LayerPlayer = LayerMask.NameToLayer("Player");
    4.         StartCoroutine(fuegoPausado());
    5.     }
    6.  
    7. private void shoot()
    8.     {
    9.         RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.up), 100f);
    10.  
    11.         if (hit.transform.gameObject.layer == LayerPlayer)
    12.         {
    13.             projectileInstant();
    14.             //Debug.Log("Disparando");
    15.            
    16.         }
    17.         else
    18.         {
    19.             canShoot = false;
    20.         }
    21.      
    22.  
    23.  
    24.     }
    The enemy fires normally when I use this code down here, however it tries to shoot you through plataforms


    Code (CSharp):
    1. private void shoot()
    2.     {
    3.         RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.up), 100f);
    4.  
    5.         if (hit)
    6.         {
    7.             projectileInstant();
    8.             //Debug.Log("Disparando");
    9.          
    10.         }
    11.         else
    12.         {
    13.             canShoot = false;
    14.         }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    First I don't see where you're even calling shoot() in the above code, so that might be something to look at.

    Second, always use named arguments with
    Physics.Raycast()
    because it contains many poorly-designed overloads:

    https://forum.unity.com/threads/lay...ke-described-in-the-docs.744302/#post-6355392

    Third, if none of that helps you, welcome to debugging. Here's how to get started:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    When in doubt, print it out!(tm)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
     
  3. Broly_MacBroly

    Broly_MacBroly

    Joined:
    Oct 19, 2022
    Posts:
    5
    Sorry, I am afraid that I am still too new in this to understand everything you said, It's a lot of info and I am overwhelmed by it, could you please explain how do I implement all that?

    and I put up only the parts of the code that I think houses the problem since the problem only happens when I put up the ".transform.gameObject.layer == LayerPlayer" code into the If(Hit) part, everything else, the detection of the player, the aiming function and the actual projectile generation works fine, the only problem I have is trying to make the raycast detect the player.

    However if seeing the whole code gives you some needed
    context here it is.

    Thank you so much for you help!

    Code (CSharp):
    1.   [SerializeField] public PolygonCollider2D fov;
    2.     [SerializeField] Disparo enemyProjectile;
    3.     [SerializeField] GameObject arm;
    4.     [SerializeField] GameObject FoV;
    5.     [SerializeField] GameObject Blaster;
    6.     [SerializeField] CircleCollider2D cqcDetector;
    7.     [SerializeField] float fireRate = 0;
    8.     [SerializeField] float interlude = 0;
    9.     [SerializeField] int shootCounter = 0;
    10.  
    11.     private int LayerPlayer;
    12.  
    13.  
    14.     [SerializeField] public bool combatModeActive = false;
    15.     [SerializeField] public bool canShoot = true;
    16.     // Start is called before the first frame update
    17.     void Start()
    18.     {
    19.         LayerPlayer = LayerMask.NameToLayer("Player");
    20.         StartCoroutine(fuegoPausado());
    21.        
    22.        
    23.  
    24.  
    25.     }
    26.  
    27.     // Update is called once per frame
    28.     void Update()
    29.     {
    30.       ActivateCombatMode();
    31.       AimAndShoot();
    32.     }
    33.  
    34.    
    35.  
    36.     private void ActivateCombatMode()
    37.     {
    38.        if (fov.IsTouchingLayers(LayerMask.GetMask(new string[] { "Player" })))
    39.         {
    40.             //Debug.Log("I See You");
    41.             combatModeActive = true;
    42.             StopCoroutine(waiter());
    43.         }
    44.         if (!fov.IsTouchingLayers(LayerMask.GetMask(new string[] { "Player" })))
    45.         {
    46.             //Debug.Log("I dont See You");
    47.            
    48.             StartCoroutine("waiter");
    49.            
    50.  
    51.             //combatModeActive = false;
    52.         }
    53.         if (cqcDetector.IsTouchingLayers(LayerMask.GetMask(new string[] { "Player" })))
    54.         {
    55.             combatModeActive = true;
    56.             StopCoroutine(waiter());
    57.         }
    58.  
    59.        
    60.        
    61.  
    62.     }
    63.     IEnumerator waiter()
    64.     {
    65.         yield return new WaitForSeconds(5);
    66.         combatModeActive = false;
    67.             StopCoroutine("waiter");
    68.        
    69.        
    70.        
    71.  
    72.     }
    73.  
    74.  
    75.     private void AimAndShoot()
    76.     {
    77.         if (combatModeActive == true)
    78.         {
    79.             Aim();
    80.             shoot();
    81.             LookAtPlayer();
    82.  
    83.         }
    84.         if (combatModeActive == false)
    85.         {
    86.             StopCoroutine(fuegoContinuo());
    87.             if (GetComponent<CombatMovementAI>().playerIsRight == true)
    88.         {
    89.            
    90.             Vector3 Ubicacion = transform.position;
    91.             Vector3 ubicacionCanon = transform.position;
    92.             Vector3 lookAtVector = Ubicacion - ubicacionCanon;
    93.             float angle = Mathf.Atan2(90, -90) * Mathf.Rad2Deg;
    94.             lookAtVector = Ubicacion + ubicacionCanon;
    95.             arm.transform.localRotation = Quaternion.Euler(0, 0, -angle);
    96.         }
    97.         else if (GetComponent<CombatMovementAI>().playerIsRight == false)
    98.         {
    99.          
    100.             Vector3 Ubicacion = transform.position;
    101.             Vector3 ubicacionCanon = transform.position;
    102.             Vector3 lookAtVector = Ubicacion - ubicacionCanon;
    103.             float angle = Mathf.Atan2(90, -90) * Mathf.Rad2Deg;
    104.             lookAtVector = Ubicacion + ubicacionCanon;
    105.             arm.transform.localRotation = Quaternion.Euler(0, 0, -angle);
    106.         }
    107.        
    108.  
    109.             //Debug.Log("It's all quiet now");
    110.         }
    111.  
    112.  
    113.     }
    114.  
    115.     private void shoot()
    116.     {
    117.         RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.up), 100f);
    118.  
    119.         if (hit)
    120.         {
    121.             projectileInstant();
    122.             //Debug.Log("Disparando");
    123.            
    124.         }
    125.         else
    126.         {
    127.             canShoot = false;
    128.         }
    129.      
    130.  
    131.  
    132.     }
    133.  
    134.     private void projectileInstant()
    135.     {
    136.         if (canShoot == true)
    137.         {
    138.             Disparo newProjectile;
    139.             newProjectile = Instantiate(enemyProjectile, Blaster.transform.position, Blaster.transform.rotation);
    140.             shootCounter --;
    141.             canShoot = false;
    142.             StartCoroutine(fuegoContinuo());
    143.  
    144.         }
    145.  
    146.      
    147.        
    148.        
    149.     }
    150.  
    151.     IEnumerator fuegoPausado()
    152.     {
    153.  
    154.        
    155.         if (shootCounter == 0)
    156.         {
    157.             yield return new WaitForSeconds(interlude);
    158.             shootCounter = 6;
    159.             canShoot = true;
    160.  
    161.            
    162.         }
    163.  
    164.     }
    165.  
    166.  
    167.     private void Aim()
    168.     {
    169.         if (combatModeActive && GetComponent<CombatMovementAI>().playerIsRight == true)
    170.         {
    171.             Movement objetivo = FindObjectOfType<Movement>();
    172.             Vector3 Ubicacion = objetivo.transform.position;
    173.             Vector3 ubicacionCanon = transform.position;
    174.             Vector3 lookAtVector = Ubicacion - ubicacionCanon;
    175.             float angle = Mathf.Atan2(lookAtVector.x, lookAtVector.y) * Mathf.Rad2Deg;
    176.             lookAtVector = Ubicacion + ubicacionCanon;
    177.             arm.transform.localRotation = Quaternion.Euler(0, 0, -angle);
    178.         }
    179.          if (combatModeActive && GetComponent<CombatMovementAI>().playerIsRight == false)
    180.         {
    181.             Movement objetivo = FindObjectOfType<Movement>();
    182.             Vector3 Ubicacion = objetivo.transform.position;
    183.             Vector3 ubicacionCanon = transform.position;
    184.             Vector3 lookAtVector = Ubicacion - ubicacionCanon;
    185.             float angle = Mathf.Atan2(-lookAtVector.x, lookAtVector.y) * Mathf.Rad2Deg;
    186.             lookAtVector = Ubicacion + ubicacionCanon;
    187.             arm.transform.localRotation = Quaternion.Euler(0, 0, -angle);
    188.             Debug.Log("Apuntando a la izquierda");
    189.  
    190.             //Debug.Log("El juegador está a la izquierda");
    191.         }
    192.  
    193.     }
    194.  
    195.  
    196.         private void LookAtPlayer()
    197. {
    198.     if (combatModeActive && GetComponent<CombatMovementAI>().playerIsRight == true)
    199.     {
    200.             Movement objetivo = FindObjectOfType<Movement>();
    201.             Vector3 mirarAlla = objetivo.transform.position;
    202.             Vector3 cosaQueMira = transform.position;
    203.             Vector3 lookAtVector = mirarAlla - cosaQueMira;
    204.             float angle = Mathf.Atan2(lookAtVector.x, lookAtVector.y) * Mathf.Rad2Deg;
    205.             lookAtVector = mirarAlla + cosaQueMira;
    206.             FoV.transform.localRotation = Quaternion.Euler(0, 0, -angle);
    207.  
    208.     }
    209.     else if (combatModeActive && GetComponent<CombatMovementAI>().playerIsRight == false)
    210.     {
    211.         Movement objetivo = FindObjectOfType<Movement>();
    212.             Vector3 mirarAlla = objetivo.transform.position;
    213.             Vector3 cosaQueMira = transform.position;
    214.             Vector3 lookAtVector = mirarAlla - cosaQueMira;
    215.             float angle = Mathf.Atan2(-lookAtVector.x, lookAtVector.y) * Mathf.Rad2Deg;
    216.             lookAtVector = mirarAlla + cosaQueMira;
    217.             FoV.transform.localRotation = Quaternion.Euler(0, 0, -angle);
    218.             Debug.Log("ahora mirando a la izquierda");
    219.  
    220.     }
    221.            
    222.  
    223.  
    224. }
    225.    
    226.  
    227.     IEnumerator fuegoContinuo()
    228.     {
    229.         if (shootCounter > 0)
    230.         {
    231.                 //Shooting();
    232.             yield return new WaitForSeconds(fireRate);
    233.             canShoot = true;
    234.             projectileInstant();
    235.         }
    236.         if (shootCounter == 0)
    237.         {
    238.             StartCoroutine(fuegoPausado());
    239.         }
    240.        
    241.    
    242.      
    243.  
    244.     }
    245. }
    246.  
     
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,500
    Raycast and pretty much all other queries has a LayerMask argument. Provide a layer-mask there to select what you're interested in. It's described in the docs. If you read it you would clearly see "Filter to detect Colliders only on certain layers." which is what you want correct?

    As an example: Add a public field "LayerMask WhatRayCastShouldHit" to your script. Select the layers in the inspector for the script. Pass this to the raycast like this:
    Code (CSharp):
    1. RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.up), 100f, WhatRayCastShouldHit);