2d balls stuck in box colliders
In this simulation, an x amount of little balls are spawned into a 2d rectangle surrounded by walls. These all follow a randomly selected movement direction. After a few minutes is allotted they all somehow end up stuck in the corners (see screenshot).
I can't find the solution. I have tried a lot from changing the physical material to trying to reverse the movement on entering the walls. The walls are also set to static and the balls are set to dynamic.
![void Start()
{
InvokeRepeating("ChangeDirection", 0, 1f);
nog_gezond = true;
}
// Update is called once per frame
void Update()
{
transform.Translate(direction * Time.deltaTime, Space.World);
}
void ChangeDirection()
{
angle = Random.Range(0.0f, 360.0f);
steps = Random.Range(0.1f, 2.0f);
direction.x = steps * Mathf.Cos(angle * Mathf.Deg2Rad);
direction.y = steps * Mathf.Sin(angle * Mathf.Deg2Rad);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Infected") && nog_gezond == true)
{
kans = Random.Range(1, 100);
if (kans <= besmetting_kans)
{
transform.gameObject.tag = "Infected";
gameObject.GetComponent<Renderer>().material.color = new Color(1.0f, 0, 0);
counter.healthy -= 1;
counter.infected += 1;
InvokeRepeating("add_days", 0, 1);
nog_gezond = false;
}
}
if (other.gameObject.CompareTag("GameController"))
{
transform.Translate(direction * Time.deltaTime * -1, Space.World);
}][1]
[1]: /storage/temp/176815-screenshot-2021-03-01-at-204328.png
Answer by tylerdtrudeau · Mar 05, 2021 at 12:49 AM
I've experienced something like this before. Do you have the physics material bouncy set to max (1)? Secondly depending on how you have the rigidbody set up on the balls then during the collisions they can start to lose velocity, slow down, and eventually stop. You can write a couple lines of script that ensures a constant velocity (something like Vector2.Reflect) and then they will never slow down or stop.
This post helped me alot, so much so I still had it bookmarked.
Cheers