How To Make A Ball Move In Unity 3D | Unity Tutorial
In this Unity 3D tutorial, discover how to implement smooth ball movement! We’ll walk you through setting up a 3D ball, adding movement controls with C# scripting, and applying forces for responsive gameplay. Ideal for beginners, this tutorial will help you get your ball rolling and gain confidence in Unity's physics and scripting systems.
WATCH FULL TUTORIAL ON YOUTUBE
=========================================================
Unity Projects - ON SALE!!!
1. Water Sort Puzzle 9000 Levels
2. Ball Sort Puzzle 9000 Levels
3. Sling Shot
=========================================================
Scripts:
BallMovement.cs
using UnityEngine;
public class BallMovement : 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
private int jumpCount = 0; // Current number of jumps
private bool isGrounded; // 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;
}
}
}
------------------------------------------------------------------------------------------------------------------------------------------
CameraFollowBall.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollowBall : MonoBehaviour
{
public Transform player; // The player's transform
public Vector3 offset; // Offset position from the player
public float smoothSpeed = 0.125f; // Speed at which the camera follows
void LateUpdate()
{
if (player != null)
{
// Calculate the desired position
Vector3 desiredPosition = player.position + offset;
// Smoothly interpolate between the camera's current position and the desired position
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
// Update the camera's position
transform.position = smoothedPosition;
}
}
}