Skip to content

Instantly share code, notes, and snippets.

@unity3dcollege
Last active August 7, 2021 21:35
Show Gist options
  • Save unity3dcollege/b43888d4d17bef0c21369d6cc32352dd to your computer and use it in GitHub Desktop.
Save unity3dcollege/b43888d4d17bef0c21369d6cc32352dd to your computer and use it in GitHub Desktop.
using UnityEngine;
public class BallBouncer : MonoBehaviour
{
[SerializeField]
[Tooltip("Just for debugging, adds some velocity during OnEnable")]
private Vector3 initialVelocity;
[SerializeField]
private float minVelocity = 10f;
private Vector3 lastFrameVelocity;
private Rigidbody rb;
private void OnEnable()
{
rb = GetComponent<Rigidbody>();
rb.velocity = initialVelocity;
}
private void Update()
{
lastFrameVelocity = rb.velocity;
}
private void OnCollisionEnter(Collision collision)
{
Bounce(collision.contacts[0].normal);
}
private void Bounce(Vector3 collisionNormal)
{
var speed = lastFrameVelocity.magnitude;
var direction = Vector3.Reflect(lastFrameVelocity.normalized, collisionNormal);
Debug.Log("Out Direction: " + direction);
rb.velocity = direction * Mathf.Max(speed, minVelocity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment