Just add a Static
rigidbody 2D to all the walls.
Edit: I noticed now two problems.
1) You haven't assigned a physics material to your ball. Create a new physics material 2D in the assets, set its Bounciness
to 1 and Friction
to 0, then drag it to the Material
of the ball's Rigidbody 2D
component. You need the Bounciness
!= 0 in order to make the ball bounce on the walls.
2) You're adding every FixedUpdate()
the same force to the ball, this will increase rapidly its velocity regardless of bounces, move the AddForce
to Start
for the moment, if you need to make further changes during runtime to the velocity of the ball, use the AddForce
under an if
statement of your choice, so it won't increase the velocity up to infinity (and making the ball go beyond the walls due to missed collision in a single physics timestep).
Edit 2: the code to randomly choose a direction but with a set speed.
using UnityEngine;
public class Ball : MonoBehaviour {
Rigidbody2D rigidbody;
Vector2 direction;
public float startSpeed;
void Start() {
rigidbody = GetComponent<Rigidbody2D>();
float radiants = 0;
while (radiants == 0) {
radiants = Random.Range(0, 2 * Mathf.PI);
}
direction = new Vector2(Mathf.Cos(radiants), Mathf.Sin(radiants));
direction.Normalize();
direction *= startSpeed;
rigidbody.AddForce(direction);
}
}