# 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? May 13, 2017 at 12:44
• But this is 3d. May 13, 2017 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);
}
direction.Normalize();
direction *= startSpeed;
}
}

• It didn't work. It's colliding, but not reflecting. May 13, 2017 at 12:37
• It's working fine now, but when I add the AddForce to start, the speed becomes always different speed. May 13, 2017 at 13:39
• You're using a random value for the initial velocity, it's working as intended by your code. Do you want to the initial velocity to be non random? And please don't forget to accept the answer. ;) May 13, 2017 at 13:44
• I want to move in a certain speed, but to a random direction. May 13, 2017 at 14:02
• The random direction as posted now is not uniformly random, you are projecting square onto unit circle which will not result in same density (more likely around corners). May 13, 2017 at 17:07