How To Make A Ball Bounce In Unity 3D | Unity Tutorial
In this Unity 3D tutorial, learn how to make a ball bounce! We’ll cover how to create a 3D sphere, apply physics materials for realistic bounces, and set up a ground plane. Follow along to see how simple adjustments can bring your ball to life with fun, dynamic bouncing effects. Perfect for Unity beginners looking to get hands-on with basic physics!
WATCH FULL TUTORIAL ON YOUTUBE
=========================================================
3 Unity Projects Only $50 - ON SALE!!!!
Contact: unitycoderz2022@gmail.com
=========================================================
Scripts:
using UnityEngine;
public class BallController : MonoBehaviour
{
public float forceAmount = 10f; // Force applied for movement
public float jumpForce = 10f; // Force applied for jumping
public int maxJumps = 2; // Maximum number of jumps (double jump in this case)
private int jumpCount = 0; // Current number of jumps
private bool isGrounded = true; // Check if the ball is on the ground
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
// Movement controls
if (Input.GetKey(KeyCode.W))
{
rb.AddForce(Vector3.forward * forceAmount);
}
if (Input.GetKey(KeyCode.S))
{
rb.AddForce(Vector3.back * forceAmount);
}
if (Input.GetKey(KeyCode.A))
{
rb.AddForce(Vector3.left * forceAmount);
}
if (Input.GetKey(KeyCode.D))
{
rb.AddForce(Vector3.right * forceAmount);
}
// Jumping
if (Input.GetKeyDown(KeyCode.Space))
{
if (isGrounded || jumpCount < maxJumps)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
jumpCount++;
}
}
}
// Check if the ball is on the ground
private void OnCollisionStay(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
jumpCount = 0; // Reset jump count when grounded
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = false;
}
}
}