How do raycasts work?

I'm struggling a lot trying to figure out the challenge where I make the shield ignore the player if they're behind a wall.  The hint says to use raycasts, but I don't remember and can't find where we ever used raycasts in this tutorial series before (I've been pretty slow so it's probably in there somewhere and I just forgot).  How do I use them?
  • Nathan Lovato replied

    We used raycasts for the bat line of sight in think on your feet, the side scroller project.

    A raycast is a line that checks for collisions. It's similar to areas in a sense, except it's a line and each frame it can report the coordinates of the point at which it collides, and which entity it collided with.

    I'll run you through the general idea, which is similar to how the bat worked. I won't give you the exact code so you still do most of the challenge.

    So here, you can create a Raycast2D node, enable it in the inspector, set its collision masks to detect both walls and the player.

    Each frame, you rotate the raycast towards the player character (the target) and check if the raycast collided. If so, you can check with what it collided. If this corresponds to the player (the mob target), it means that you have a clear line of sight on the player character.

    If you need a reference for the code, I invite you to check the side scrolling module and see if you can adapt what you learned there to this slightly different context (coding independently is a lot about that, transferring things you've learned somewhere to a different project or context).

    Let me know if you need anything else!

  • T
    Typical_Name replied

    Yeah, the concept of raycasts is something I get, it's the execution I was struggling with.  It turns out I actually had the code and collision mask setup right, the only problem being that the "enabled" box on the raycast was checked off by default.  >_<

  • Nathan Lovato replied

    Ah yes, in Godot 3 they're disabled by default! In Godot 4 they were made enabled by default now.