In the program, the texture runs back and forth randomly, and if it hits the walls, it changes the direction of movement. Everything is good, but the texture is controlled by two methods, one for reflection from the walls, the other for the chaotic movement. When they match, and the texture is close to the wall - it can pass through the wall.
How can something be done so that under no circumstances could it pass through the wall? Walls with Box Collider 2d and Rigidbody 2d
Why not under any circumstances - because this problem was even before the random element. Just sometimes, leave the texture to run across the field, and in half an hour it will fly through the wall as if nothing had happened. And with the random, this has always happened.
code
{ Vector2 dir; Transform myTransform; public float angle; public float vx = 1f; public float vy = 1f; public float speed = 1f; void Start() { InvokeRepeating("Running", 2, 3); myTransform = transform; dir = Vector2.up; myTransform.localRotation = Quaternion.Euler(0, 0, angle); } void Running() { var random = Random.Range(-10, 10); var random1 = Random.Range(-10, 10); var random3 = Random.Range(-10, 10); vy = random1; vx = random; angle = Vector2.Angle(Vector2.right, new Vector2(vy, vx)); if (random3 > 0) { angle = -angle; } dir = Vector2.up; myTransform.localRotation = Quaternion.Euler(0, 0, angle); } void Update() { myTransform.Translate(dir * speed * Time.deltaTime); } void OnTriggerEnter2D(Collider2D coll) { if (coll.gameObject.name.StartsWith("bbot")) { myTransform.localRotation = Quaternion.Euler(0, 0, angle - Random.Range(-80, 80)); } if (coll.gameObject.name.StartsWith("bleft")) { myTransform.localRotation = Quaternion.Euler(0, 0, angle + Random.Range(185, 350)); } if (coll.gameObject.name.StartsWith("bright")) { myTransform.localRotation = Quaternion.Euler(0, 0, angle - Random.Range(185, 350)); } if (coll.gameObject.name.StartsWith("btop")) { myTransform.localRotation = Quaternion.Euler(0, 0, angle - Random.Range(100, 260)); } }