Detect 3D Collision using filter

Hi guys, I followed a YT tutorial for 2D Boid, after that I transform everything in 3D cause I wanna try to make my aquarium :smile:
But I cant get the fish avoid the glass and they go through.
Can somebody tell me what is wrong in my script? I think I dont get the correct distance of the object:

TLDR: skip to the latest class to see where the magic should happens
My Boid class:

    void Update()
    {
        foreach(BoidAgent agent in agentsList)
        {
            List<Transform> context = GetNearbyObjects(agent);

            Vector3 move = behaviour.CalculateMove(agent, context, this);
            move *= driveFactor;
            if (move.sqrMagnitude > squareMaxSpeed)
            {
                move = move.normalized * maxSpeed;
            }

            agent.Move(move);
        }
    }
  
    private List<Transform> GetNearbyObjects(BoidAgent agent)
    {
        List<Transform> context = new();
        Collider[] contextColliders = Physics.OverlapSphere(agent.transform.position, squareAvoidanceRadius);
        foreach (Collider c in contextColliders)
        {
            if (c != agent.AgentCollider)
            {
                context.Add(c.transform);
            }
        }
        return context;
    }

This is the Agent:

    Boid agentBoid;
    public Boid AgentBoid => agentBoid;
  
    Collider agentCollider;
    public Collider AgentCollider => agentCollider;  
    void Start()
    {
        agentCollider = GetComponent<Collider>();
    }

    public void Initialize(Boid boid)
    {
        agentBoid = boid;
      
    }
    public void Move(Vector3 velocity)
    {
        transform.up = velocity;
        transform.position += (Vector3)velocity * Time.deltaTime;       
    }

And this is a behaviour:

public class Alignment : FilterBoidBehaviour
{
    public override Vector3 CalculateMove(BoidAgent agent, List<Transform> context, Boid boid)
    {
        if (context.Count == 0)
            return agent.transform.up;

        Vector3 alignmentMove = Vector3.zero;

        List<Transform> filteredContext = (filter == null) ? context : filter.Filter(agent, context);
        foreach (Transform item in filteredContext)
        {
            alignmentMove += (Vector3)item.transform.up;
        }
        alignmentMove /= context.Count;

        return alignmentMove;
    }
}

I applied a filter to this behaviour and the filter should avoid stuff. Here is the filter I used:

public class PhysicsLayerFilter : ContextFilter
{
    public LayerMask mask;
    public float detectionRadius = 5.5f;
    public override List<Transform> Filter(BoidAgent agent, List<Transform> originalList)
    {
        List<Transform> filtered = new();
        foreach (Transform item in originalList)
        {
            // 2D Version
            //if (mask == (mask | (1 << item.gameObject.layer)))
            //{
            //    filtered.Add(item);
            //}
          
            // 3D Version
            // Calc dist between agent and object
            float distance = Vector3.Distance(agent.transform.position, item.position);
            if (distance <= detectionRadius)
            {
                filtered.Add(item);
            }
        }
        return filtered;
    }
}

What is wrong with my code?
I have weights that works.
My Boid prefab has a Capsule collider and also the aquarium walls, but they cant get stopped.

Thank you everybody


9406559--1317011--upload_2023-10-13_1-59-32.png
9406559--1317014--upload_2023-10-13_1-59-49.png
9406559--1317017--upload_2023-10-13_1-59-57.png

The difference between Layers vs LayerMasks:

“There are 10 types of people in this world: those who understand binary, and those who don’t.”

Otherwise, sounds like it is…

Time to start debugging! Here is how you can begin your exciting new debugging adventures:

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 names of the GameObjects or Components involved?
  • 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.

Visit Google for how to see console output from builds. 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 for iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

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.

If your problem is with OnCollision-type functions, print the name of what is passed in!

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:

“When in doubt, print it out!™” - Kurt Dekker (and many others)

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

And so you know, Line 21 creates as whole new list which is then thrown away and Line 22 likewise creates a whole new array which is also then thrown away. You’re doing this per-frame so you’ll produce a lot of waste. This kind of stuff, whilst convenient, isn’t good for performance, something which a boids simulation is typically known for.

Provide a list to be populated that you reuse and use the 3D physics queries that allow you to provide an array to be reused too.

Im not at that point yet.
I get your point of view and yes, it’s pure waste but at my stage I dont know where to implement a List to populate and neither how to use 3D physics queries.
Im gonna try to fix my collision problem before, then I try to increase the number of boid and try to improve performance, so that 1-2k boid can swim all togheter :smile:

Maybe I just missed it, but I don’t see anywhere in the script where you are actually preventing agents from moving based on collision.