Last active
August 7, 2021 21:35
-
-
Save unity3dcollege/b43888d4d17bef0c21369d6cc32352dd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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