Search Unity

Question Physics.Raycast, layers problem. Unity 2020.2.0f1

Discussion in 'Scripting' started by a4chteam, Dec 25, 2020.

  1. a4chteam

    a4chteam

    Joined:
    Dec 22, 2020
    Posts:
    22
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class DistanceChecker : MonoBehaviour
    4. {
    5.     //Checking collision status;
    6.     public bool Faced = false;
    7.  
    8.     //The object that plays the animation;
    9.     public GameObject ObjectAnimation;
    10.  
    11.     void FixedUpdate()
    12.     {
    13.         int layerMask = 0 << 7;
    14.         layerMask = ~layerMask;
    15.  
    16.         RaycastHit hit;
    17.         Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, 1.4f, layerMask);
    18.         if (hit.collider != null && Faced == false)
    19.         {
    20.             Faced = true;
    21.             ObjectAnimation.GetComponent<Animator>().SetBool("Check", true);
    22.             Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
    23.         }
    24.         else if (hit.collider == null && Faced == true)
    25.         {
    26.             Faced = false;
    27.             ObjectAnimation.GetComponent<Animator>().SetBool("Check", false);
    28.         }
    29.     }
    30. }
    These lines don't work. Ray collides with objects of these layers and reacts.
    Code (CSharp):
    1.         int layerMask = 0 << 7;
    2.         layerMask = ~layerMask;
    And the change of a variable to bool occurs with a delay.
    Code (CSharp):
    1. ObjectAnimation.GetComponent<Animator>().SetBool("Check", true);
    Because of this, the animation loses with a delay too.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,726
    This takes zero and shifts it left 7 positions and ends up with ... zero.

    That's probably not what you want.

    You probably want to take 1 and shift it left by whatever number of bits your desired layer is. Usually the first user-usable layer is 8, not 7, so not sure what layer you are after. There are also LayerMask class helper functions to get you out of this direct bit fiddling you are doing.
     
    a4chteam likes this.