Search Unity

Raycast going through objects

Discussion in 'Getting Started' started by magmu78, Aug 18, 2023.

  1. magmu78

    magmu78

    Joined:
    Aug 14, 2022
    Posts:
    2
    Hello Im making a game and I raycasts are going through walls.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class GrannyEye : MonoBehaviour
    6. {
    7.     public GameObject granny;
    8.     public float raycastDist;
    9.  
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.      
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update()
    18.     {
    19.         RaycastHit hitInfo;
    20.         Vector3 fwd = transform.TransformDirection(Vector3.forward);
    21.         Debug.DrawRay(transform.position, fwd * raycastDist, Color.red);
    22.         if (Physics.Raycast(transform.position, fwd, out hitInfo, raycastDist) && hitInfo.collider.gameObject.tag == "Player")
    23.         {
    24.             granny.GetComponent<EnemyAIGranny>().seePlayer = true;
    25.         }
    26.         else
    27.         {
    28.             granny.GetComponent<EnemyAIGranny>().seePlayer = false;
    29.         }
    30.     }
    31. }
    this is the code for it and when I shoot a raycast its going through objects like cubes and walls and doors, please help me fix that. in every script I write that contains raycasts, the raycasts are just going through objects. the objects have a collider, a mesh renderer, a mesh filter but raycasts are still going through them. please help me proof 1.png
     

    Attached Files:

  2. Reaktion

    Reaktion

    Joined:
    Nov 8, 2019
    Posts:
    53
    Hi,

    The visual line that you're seeing is I believe drawn by this line of code :
    Debug.DrawRay(transform.position, fwd * raycastDist, Color.red);

    Here, the ray will always be at the same size, and will never stop at an object.

    If you want to draw a ray that will stop at the first collider, you have to change the ray anytime the raycast is hitting something.

    Like this :
    Code (CSharp):
    1. if (Physics.Raycast(transform.position, fwd, out hitInfo, raycastDist) && hitInfo.collider.gameObject.tag == "Player"))
    2. {
    3.     Debug.DrawRay(transform.position, fwd * hitInfo.distance, Color.red);
    4.     granny.GetComponent<EnemyAIGranny>().seePlayer = true;
    5. }
    With this code, ray will not be drawn if nothing's hit. Up to you if you want to keep the current behaviour you're having.

    Hope this helps !
     
  3. magmu78

    magmu78

    Joined:
    Aug 14, 2022
    Posts:
    2
    The problem is, with other rays raycasts are still going through walls, like when I wanna open a door, I shoot a raycast. but now I can open doors through walls