Bouncing balls with collision from any 2Dcolliders/wall can be achieved by putting continuous force to the game object and assign a physics material to the game object you like to bounce on collision.
1. Gameobject must have rigidbody attached to it with 0 gravity.
2. Gameobject must have a 2D collider with a 2d physics Material having 0 friction and 0.8 bounce.
3. Assign a script name BouncingObjects having the following line of code in it.
using UnityEngine;
using System.Collections;
public class BouncingObjects : MonoBehaviour {
float x,y;
public float Speed=1f;//can be vary manually
// Use this for initialization
void Start ()
{
x = Random.Range (-1, 2);
y = Random.Range (-1, 2);
}
// continously assigning x and y.
void FixedUpdate ()
{
this.transform.GetComponent<Rigidbody2D> ().AddForce(new Vector2 (x,y)*Speed,ForceMode2D.Force);
}
//Changing x and y on collision
void OnCollisionEnter2D(Collision2D coll)
{
if (x < 0)
x = 1;
else if (x > 0)
x = -1;
else
x = 1;
if (y < 0)
y = 1;
else if (y > 0)
y = -1;
else
y = -1;
}
}
0 Comment(s)