Hi, I have an English project in which I’m making a game for, and in the game I need to have an eyeball randomly bounce around in a box (side to side, up and down, completely at random). I tried placing in a ball with a very bouncy physics material, yet it only bounced up and down. Any help?
How random do you want it to bounce? Unity’s physics engine will try to be realistic. If you want it to bounce around, you’ll need to give it an initial push in some direction. You can use AddForce() on the rigidbody to get it moving in a direction, and let the physics engine take over.
Note that too bounce for a while, you’ll need to add a Physic Material with a high bounce value to the ball.
If you really want unrealistic, random bounding, one approach is to make the ball spin. When it lands while spinning, the spin will cause it to bounce in a different direction. This script can be added to the object to cause it to bound randomly.
public class RandomBounce : MonoBehaviour
{
Rigidbody _rb;
void Start()
{
_rb = GetComponent<Rigidbody>();
// Increase max angular velocity or we won't see much spin.
_rb.maxAngularVelocity = 1000;
StartCoroutine(ChangeRotation());
}
private IEnumerator ChangeRotation()
{
while (true)
{
_rb.AddTorque(new Vector3(10 * UnityEngine.Random.Range(0, 1f), UnityEngine.Random.Range(0, 1f), UnityEngine.Random.Range(0, 1f)), ForceMode.Impulse);
yield return new WaitForSeconds(1);
}
}
}
Hey! Thanks so much for the fast reply! I put the code into the project and messed with it a little and got some good results! Thanks, hopefully I’ll get a good grade!
public class BallBounce : MonoBehaviour
{
Rigidbody _rb;
void Start()
{
_rb = GetComponent<Rigidbody>();
// Increase max angular velocity or we won't see much spin.
_rb.maxAngularVelocity = 1000;
StartCoroutine(ChangeRotation());
}
private IEnumerator ChangeRotation()
{
while (true)
{
_rb.AddTorque(new Vector3(10 * UnityEngine.Random.Range(0, 3f), UnityEngine.Random.Range(0, 3f), UnityEngine.Random.Range(0, 3f)), ForceMode.VelocityChange);
yield return new WaitForSeconds(1);
}
}
}