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
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