# Bounce ball after collision

I added Box Collisions (Walls) outside of the screen and a player (ball) with rigidbody and Circle Collider in dynamic forcing to a random direction.

I want the ball to bounce when it collides the wall.

Bomb.cs

private Rigidbody2D rigidbody;
private Vector2 direction;

// Use this for initialization
void Start () {
rigidbody = gameObject.GetComponent<Rigidbody2D> ();
direction = new Vector2 (Random.value, Random.value);
}

// Update is called once per frame
void FixedUpdate () {
}


• I am not an expert on physics, but perhaps you will find bouncing ball tutorial helpful? – wondra May 13 '17 at 12:44
• But this is 3d. – Eucar May 13 '17 at 12:59

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>();
radiants = Random.Range(0, 2 * Mathf.PI);
}