This is a significant undertaking, combining several advanced 2D physics and character control techniques. We'll build a Unity project from the ground up, covering:
- New Input System Setup: Creating an
Input Action Asset.
- Core Player Controller (
PlayerController): Manages input, applies movement, handles rotation to slopes.
- State Machine: Defines different player behaviors (Ground, Air, Jump).
- Collision Handling: Using
Rigidbody2D.SweepTest for robust, high-speed collision detection to prevent tunneling.
- Moving Platforms: Proper interaction by parenting or transferring velocity.
- One-Way Platforms: Integration with Unity's
Platform Effector 2D.
- Custom Physics for Slopes: Gravity and movement applied relative to the ground normal.
Let's break it down!
Project Setup & Prerequisites
- Create a New Unity 2D Project.
- Install New Input System:
- Go to
Window > Package Manager.
- Select
Unity Registry.
- Search for "Input System" and
Install it.
- When prompted to enable the new input backend, select
Yes. Unity will restart.
1. Input System Setup
- Create Input Actions Asset:
- In your
Assets folder, right-click Create > Input Actions. Name it PlayerInputActions.
- Double-click
PlayerInputActions to open the editor.
- Create an Action Map: Click the
+ next to "Action Maps" and name it Player.
- Add Actions:
- Move:
- Click the
+ next to "Actions". Name it Move.
- Set
Action Type to Value, Control Type to Vector2.
- Click the
+ next to Move to add bindings.
- Binding 1:
Path: <Gamepad>/leftStick (for gamepad).
- Binding 2:
Path: <Keyboard>/a (and d, w, s for WASD). Change Interaction to D-pad, Processors to Stick Deadzone(0.1).
- Alternatively, for Keyboard only, use a
2D Vector composite:
- Right-click
Move action, Add 2D Vector Composite.
- Name it
WASD.
- Set
Up: <Keyboard>/w, Down: <Keyboard>/s, Left: <Keyboard>/a, Right: <Keyboard>/d.
- Jump:
- Click the
+ next to "Actions". Name it Jump.
- Set
Action Type to Button.
- Add Binding:
Path: <Keyboard>/space
- Add Binding:
Path: <Gamepad>/buttonSouth (A button on Xbox, X on PlayStation)
- Save Asset (Ctrl+S or Cmd+S).
2. Game Objects Setup
-
Player GameObject:
- Create an empty GameObject:
Create > Create Empty. Name it Player.
- Add a
Sprite Renderer component. Assign a simple sprite (e.g., a square) for visualization.
- Add a
Rigidbody2D component:
Body Type: Dynamic
Gravity Scale: 0 (we'll handle gravity manually for Sonic-like physics)
Collision Detection: Continuous (Crucial for preventing tunneling at high speeds!)
Freeze Rotation: Z (We'll rotate the sprite, but the Rigidbody's physics rotation should be fixed).
- Add a
CapsuleCollider2D component:
- Adjust
Size and Offset to fit your player sprite. A vertical capsule works best for slopes.
- Add a
PlayerInput component:
Actions: Drag your PlayerInputActions asset here.
Default Scheme: Keyboard&Mouse or Gamepad (or both).
Behavior: Invoke Unity Events (or Send Messages if you prefer).
- Crucially: Set up the events. In the
PlayerInput component, expand the Player map, then the Move and Jump actions.
- For
Move, add an event and drag your Player object onto it. Select PlayerController.OnMove.
- For
Jump, add an event and drag your Player object onto it. Select PlayerController.OnJump.
-
Grounds & Platforms:
- Create several
Sprite Renderer + BoxCollider2D objects for ground. Make some flat, some at angles (e.g., 20-45 degrees rotation).
- One-Way Platform: Create a
Sprite Renderer + BoxCollider2D. Add a Platform Effector 2D component. Check Use One Way and set Surface Arc to 180.
- Moving Platform: Create a + . Add a component. Set to . Create a simple script (e.g., ) to move it back and forth using or .
3. PlayerController Script
This is the core of the system. Create a new C# script named PlayerController and paste the following code.
using UnityEngine;
using UnityEngine.InputSystem;
using System.Collections.Generic; // For List<RaycastHit2D>
// Base abstract class for player states
public abstract class PlayerState
{
protected PlayerController player;
protected Rigidbody2D rb;
protected CapsuleCollider2D playerCollider;
public PlayerState(PlayerController player, Rigidbody2D rb, CapsuleCollider2D playerCollider)
{
this.player = player;
this.rb = rb;
this.playerCollider = playerCollider;
}
public virtual void EnterState() { }
public virtual void ExitState() { }
public virtual void UpdateState() { }
public virtual void FixedUpdateState() { }
public virtual void OnMoveInput(Vector2 input) { }
public virtual void OnJumpInput(bool pressed) { }
}
// Grounded State
public class GroundState : PlayerState
{
public GroundState(PlayerController player, Rigidbody2D rb, CapsuleCollider2D playerCollider) : base(player, rb, playerCollider) { }
public override void EnterState()
{
player.currentSpeed = rb.velocity.magnitude; // Maintain speed on landing
}
public override void FixedUpdateState()
{
// Apply ground movement
float targetSpeed = player.moveInput.x * player.maxGroundSpeed;
float accel = player.acceleration;
if (Mathf.Abs(player.moveInput.x) < 0.1f) // Decelerate if no input
{
accel = player.deceleration;
targetSpeed = 0; // Target 0 speed
}
// Apply acceleration/deceleration
player.currentSpeed = Mathf.MoveTowards(player.currentSpeed, targetSpeed, accel * Time.fixedDeltaTime);
// Apply speed along the ground's right vector
Vector2 groundMovement = player.transform.right * player.currentSpeed;
// Add gravity component (always pulling down the slope)
groundMovement += (Vector2)player.transform.up * -player.groundGravity;
// Apply friction
if (Mathf.Abs(player.moveInput.x) < 0.1f && player.currentSpeed != 0)
{
player.currentSpeed = Mathf.MoveTowards(player.currentSpeed, 0, player.groundFriction * Time.fixedDeltaTime);
}
// Apply the calculated velocity, but let SweepTest handle the actual movement
player.targetVelocity = groundMovement;
// Rotate player to match ground normal (Sonic-like)
Quaternion targetRotation = Quaternion.FromToRotation(Vector3.up, player.groundNormal);
player.transform.rotation = Quaternion.Slerp(player.transform.rotation, targetRotation, player.slopeAlignSpeed * Time.fixedDeltaTime);
// Check for state transitions
if (!player.IsGrounded())
{
player.ChangeState(player.airState);
}
}
public override void OnJumpInput(bool pressed)
{
if (pressed)
{
player.ChangeState(player.jumpState);
}
}
}
// Air State (Falling)
public class AirState : PlayerState
{
public AirState(PlayerController player, Rigidbody2D rb, CapsuleCollider2D playerCollider) : base(player, rb, playerCollider) { }
public override void EnterState()
{
// Detach from platform if currently parented
player.transform.parent = null;
}
public override void FixedUpdateState()
{
// Air movement (less control)
Vector2 airMovement = rb.velocity; // Keep current velocity
// Apply horizontal air control
float horizontalTargetSpeed = player.moveInput.x * player.maxAirSpeed;
airMovement.x = Mathf.MoveTowards(airMovement.x, horizontalTargetSpeed, player.airAcceleration * Time.fixedDeltaTime);
// Apply gravity
airMovement += Vector2.down * player.airGravity * Time.fixedDeltaTime;
// Apply air friction
airMovement.x = Mathf.MoveTowards(airMovement.x, 0, player.airFriction * Time.fixedDeltaTime);
player.targetVelocity = airMovement;
// Reset rotation when in air (or gradually return to upright)
Quaternion targetRotation = Quaternion.identity; // Upright
player.transform.rotation = Quaternion.Slerp(player.transform.rotation, targetRotation, player.airRotationSpeed * Time.fixedDeltaTime);
// Check for state transitions
if (player.IsGrounded())
{
player.ChangeState(player.groundState);
}
}
// Allow air control, but no jumping mid-air (unless double jump etc.)
public override void OnMoveInput(Vector2 input)
{
player.moveInput = input;
}
}
// Jump State
public class JumpState : AirState
{
public JumpState(PlayerController player, Rigidbody2D rb, CapsuleCollider2D playerCollider) : base(player, rb, playerCollider) { }
public override void EnterState()
{
base.EnterState(); // Call base AirState EnterState to detach from platform
// Apply jump force upwards relative to player's current up vector
rb.velocity = Vector2.zero; // Clear current velocity to ensure consistent jump height
rb.AddForce(player.transform.up * player.jumpForce, ForceMode2D.Impulse);
// This is a short-lived state, immediately transition to AirState
player.ChangeState(player.airState);
}
}
// Main Player Controller
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(CapsuleCollider2D))]
public class PlayerController : MonoBehaviour
{
// === Public Inspector Variables ===
[Header("Movement")]
public float maxGroundSpeed = 10f;
public float maxAirSpeed = 8f;
public float acceleration = 60f;
public float deceleration = 100f;
public float groundFriction = 50f;
public float airAcceleration = 20f;
public float airFriction = 5f;
[Header("Jump")]
public float jumpForce = 20f;
public float groundCheckDistance = 0.2f;
public LayerMask groundLayer; // Layer for ground and platforms
[Header("Physics")]
public float groundGravity = 30f; // Gravity when on slopes (pulls down slope)
public float airGravity = 20f; // Standard air gravity
public float slopeAlignSpeed = 10f; // How fast player rotates to match slope
public float airRotationSpeed = 5f; // How fast player returns to upright in air
public float skinWidth = 0.01f; // Small offset to prevent getting stuck in walls
// === Private Internal Variables ===
internal Rigidbody2D rb;
internal CapsuleCollider2D playerCollider;
internal Vector2 moveInput;
internal Vector2 groundNormal = Vector2.up; // Default to flat ground
internal float currentSpeed; // Current magnitude of speed along ground
internal Vector2 targetVelocity; // Velocity calculated by state machine
// === State Machine ===
internal PlayerState currentState;
internal GroundState groundState;
internal AirState airState;
internal JumpState jumpState;
// === Moving Platform Handling ===
private Transform currentMovingPlatform = null;
private Vector2 lastPlatformPosition;
void Awake()
{
rb = GetComponent<Rigidbody2D>();
playerCollider = GetComponent<CapsuleCollider2D>();
// Initialize states
groundState = new GroundState(this, rb, playerCollider);
airState = new AirState(this, rb, playerCollider);
jumpState = new JumpState(this, rb, playerCollider);
// Set initial state
ChangeState(groundState);
// Set the ground layer in the inspector!
if (groundLayer.value == 0) Debug.LogWarning("Ground Layer not set! Please set the 'Ground Layer' in the Inspector for PlayerController.");
}
void Update()
{
// Update state logic
currentState.UpdateState();
// Debug visualization of ground normal
Debug.DrawRay(transform.position, groundNormal * 1f, Color.blue);
Debug.DrawRay(transform.position, transform.right * 1f, Color.red);
Debug.DrawRay(transform.position, transform.up * 1f, Color.green);
}
void FixedUpdate()
{
// Update state physics logic
currentState.FixedUpdateState();
// Perform the actual movement using SweepTest for tunneling prevention
MovePlayer(targetVelocity * Time.fixedDeltaTime);
// Update ground status and normal *after* movement, but *before* next state evaluation
UpdateGroundDetection();
// Handle moving platform parenting
HandleMovingPlatforms();
}
// --- Input System Callbacks ---
public void OnMove(InputAction.CallbackContext context)
{
moveInput = context.ReadValue<Vector2>();
currentState.OnMoveInput(moveInput);
}
public void OnJump(InputAction.CallbackContext context)
{
if (context.performed)
{
currentState.OnJumpInput(true);
}
else if (context.canceled)
{
currentState.OnJumpInput(false);
}
}
// --- State Machine Logic ---
public void ChangeState(PlayerState newState)
{
if (currentState != null)
{
currentState.ExitState();
}
currentState = newState;
currentState.EnterState();
}
// --- Ground Detection ---
public bool IsGrounded()
{
// Use a BoxCast downwards slightly smaller than player's collider width for stability
// This prevents catching on very small bumps
Vector2 boxSize = new Vector2(playerCollider.size.x * 0.9f, playerCollider.size.y * 0.5f);
Vector2 origin = rb.position + playerCollider.offset;
// Offset origin slightly down for more reliable ground detection
origin.y -= playerCollider.size.y / 2f - skinWidth;
RaycastHit2D hit = Physics2D.BoxCast(origin, boxSize, 0f, Vector2.down, groundCheckDistance, groundLayer);
return hit.collider != null;
}
private void UpdateGroundDetection()
{
// Use multiple raycasts or a BoxCast to find the ground normal accurately
// We'll use a BoxCast from the center, slightly below the player.
Vector2 boxOrigin = rb.position + playerCollider.offset;
Vector2 boxSize = new Vector2(playerCollider.size.x * 0.9f, playerCollider.size.y * 0.1f); // Thin box at the bottom
RaycastHit2D[] hits = Physics2D.BoxCastAll(boxOrigin, boxSize, 0f, Vector2.down, groundCheckDistance, groundLayer);
if (hits.Length > 0)
{
// Find the lowest hit, or the hit with the closest normal to player's current 'up'
RaycastHit2D bestHit = new RaycastHit2D();
float minDistance = float.MaxValue;
// Prioritize hits that are "below" the player and close
foreach (var hit in hits)
{
if (hit.collider.transform != transform.parent) // Ignore self or parented platform
{
if (hit.distance < minDistance && hit.normal.y > 0.1f) // Ensure it's an upward-facing normal
{
minDistance = hit.distance;
bestHit = hit;
}
}
}
if (bestHit.collider != null)
{
groundNormal = bestHit.normal;
currentMovingPlatform = bestHit.rigidbody != null && bestHit.rigidbody.bodyType == RigidbodyType2D.Kinematic ? bestHit.rigidbody.transform : null;
}
else
{
groundNormal = Vector2.up; // No valid ground hit, reset to default
currentMovingPlatform = null;
}
}
else
{
groundNormal = Vector2.up; // No ground hit, reset to default
currentMovingPlatform = null;
}
}
// --- High-Speed Movement & Collision ---
private void MovePlayer(Vector2 deltaPosition)
{
Vector2 startPosition = rb.position;
Vector2 targetPosition = rb.position + deltaPosition;
// SweepTest to find collisions along the path
// Use a list to collect all hits and prioritize
List<RaycastHit2D> hits = new List<RaycastHit2D>();
int numHits = rb.SweepTest(deltaPosition.normalized, deltaPosition.magnitude + skinWidth, hits, true);
RaycastHit2D finalHit = new RaycastHit2D();
float minFraction = 1f;
// Iterate through hits to find the earliest valid collision
for (int i = 0; i < numHits; i++)
{
RaycastHit2D hit = hits[i];
// Ignore triggers and self-collision
if (hit.collider.isTrigger || hit.collider == playerCollider) continue;
// One-way platforms: allow passing through from below
if (hit.collider.usedByEffector && hit.collider.GetComponent<PlatformEffector2D>() != null)
{
// Check if coming from below the platform. If player is above platform, this should not be true.
if (Vector2.Dot(deltaPosition.normalized, Vector2.down) < 0 && hit.normal.y < 0.9f) // If moving up AND hit a downward-facing side
{
continue; // Skip this hit, we can pass through
}
if (Vector2.Dot(player.transform.up, hit.normal) < 0.1f) // If player's "up" is not aligned with platform's normal (i.e., not landing on top)
{
continue; // Skip this hit
}
}
// Ensure we hit something solid that should stop us
if (hit.fraction < minFraction)
{
minFraction = hit.fraction;
finalHit = hit;
}
}
// Adjust movement based on hit
if (finalHit.collider != null)
{
// Move up to the hit point minus skinWidth
Vector2 adjustedDelta = deltaPosition.normalized * (finalHit.distance - skinWidth);
rb.MovePosition(startPosition + adjustedDelta);
// Reflect/Slide along the hit normal if needed
// This is crucial for sliding along walls/slopes
Vector2 remainingDelta = deltaPosition - adjustedDelta;
float dot = Vector2.Dot(remainingDelta, finalHit.normal);
Vector2 slideVector = remainingDelta - dot * finalHit.normal;
// Re-apply a small slide along the surface
if (slideVector.magnitude > 0.001f) // Only slide if there's actual remaining movement
{
// This recursive call handles chained collisions (e.g., hitting a corner and sliding into another wall)
MovePlayer(slideVector);
}
// Dampen velocity component perpendicular to collision normal
Vector2 perpendicularVelocity = Vector2.Dot(rb.velocity, finalHit.normal) * finalHit.normal;
rb.velocity -= perpendicularVelocity * 0.9f; // Reduce velocity component into the wall
targetVelocity -= perpendicularVelocity * 0.9f;
}
else
{
// No collision, move as planned
rb.MovePosition(targetPosition);
}
}
// --- Moving Platform Logic ---
private void HandleMovingPlatforms()
{
if (currentMovingPlatform != null && IsGrounded())
{
// If we just landed on a platform, store its position
if (transform.parent != currentMovingPlatform)
{
transform.parent = currentMovingPlatform;
lastPlatformPosition = currentMovingPlatform.position;
}
else // If already parented
{
// Calculate platform's movement and apply to player's rigidbody velocity
Vector2 platformDelta = (Vector2)currentMovingPlatform.position - lastPlatformPosition;
// Add platform's movement directly to the player's velocity
rb.velocity += platformDelta / Time.fixedDeltaTime;
targetVelocity += platformDelta / Time.fixedDeltaTime;
lastPlatformPosition = currentMovingPlatform.position;
}
}
else if (transform.parent != null && transform.parent.GetComponent<Rigidbody2D>() != null && transform.parent.GetComponent<Rigidbody2D>().bodyType == RigidbodyType2D.Kinematic)
{
// If we are parented but no longer grounded on *that specific* platform
// OR if currentMovingPlatform became null (meaning we're not on *any* moving platform)
transform.parent = null;
}
}
// Visual debugging for the BoxCast in IsGrounded()
void OnDrawGizmos()
{
if (playerCollider == null) return;
Gizmos.color = Color.yellow;
Vector2 boxSize = new Vector2(playerCollider.size.x * 0.9f, playerCollider.size.y * 0.5f);
Vector2 origin = (Vector2)transform.position + playerCollider.offset;
origin.y -= playerCollider.size.y / 2f - skinWidth;
// Draw the ground check box
Gizmos.DrawWireCube(origin + Vector2.down * groundCheckDistance / 2, new Vector3(boxSize.x, groundCheckDistance, 0));
// Draw the normal detection box
Gizmos.color = Color.magenta;
Vector2 normalBoxOrigin = (Vector2)transform.position + playerCollider.offset;
Vector2 normalBoxSize = new Vector2(playerCollider.size.x * 0.9f, playerCollider.size.y * 0.1f);
Gizmos.DrawWireCube(normalBoxOrigin + Vector2.down * groundCheckDistance / 2, new Vector3(normalBoxSize.x, groundCheckDistance, 0));
}
}
4. Moving Platform Script (Example)
Create a new C# script named MovingPlatform and attach it to your moving platform GameObject.
using UnityEngine;
public class MovingPlatform : MonoBehaviour
{
public Vector2 moveDirection = Vector2.right;
public float moveDistance = 5f;
public float moveSpeed = 2f;
private Vector2 startPosition;
private Vector2 endPosition;
private bool movingToEnd = true;
void Start()
{
startPosition = transform.position;
endPosition = startPosition + moveDirection.normalized * moveDistance;
}
void FixedUpdate()
{
Vector2 currentTarget = movingToEnd ? endPosition : startPosition;
transform.position = Vector2.MoveTowards(transform.position, currentTarget, moveSpeed * Time.fixedDeltaTime);
if (Vector2.Distance(transform.position, currentTarget) < 0.01f)
{
movingToEnd = !movingToEnd;
}
}
}
5. Unity Editor Configuration
-
Player GameObject:
- Attach the
PlayerController script to your Player GameObject.
- In the
PlayerController component:
- Ground Layer: Create a new Layer (e.g., "Ground") in
Tags & Layers > Layers. Assign this layer to all your ground and platform GameObjects. Then, select this layer in the PlayerController's Ground Layer dropdown.
- Adjust
Ground Check Distance, Jump Force, Max Ground Speed, Acceleration, Gravity values to get the feel you want. Ground Check Distance should be slightly more than skinWidth but not too large.
-
Ensure all ground/platform objects have their Layer set to "Ground" (or whatever you picked).
-
Test: Run the game. You should be able to move your player, jump, and see it align with slopes. Test with moving and one-way platforms.
Explanation of Key Concepts:
- State Machine:
PlayerState is an abstract base class defining common methods (EnterState, ExitState, UpdateState, FixedUpdateState, OnMoveInput, OnJumpInput).
GroundState, AirState, JumpState are concrete implementations, each handling specific logic for its state.
PlayerController holds the currentState and manages ChangeState transitions based on conditions (e.g., IsGrounded(), jump input).
- Sonic-like Slope Movement:
PlayerController.groundNormal: This Vector2 is obtained by a BoxCastAll downwards, specifically picking the normal of the surface directly below the player.
Quaternion.FromToRotation(Vector3.up, player.groundNormal): Calculates the rotation needed to make the player's up vector align with the ground normal. Quaternion.Slerp smoothly applies this rotation.
player.transform.right * player.currentSpeed: Movement is applied along the player's local right vector, which is now aligned with the slope, making the player roll along the terrain.
player.transform.up * -player.groundGravity: Gravity is applied downwards relative to the player's current up vector, effectively pulling them down the slope when on it.
- No Tunneling (SweepTest):
Rigidbody2D.SweepTest: This method is crucial. Instead of just setting rb.position directly, SweepTest casts the Rigidbody2D's collider along a path and returns all hits before the actual movement.
- The
MovePlayer method calculates the desired movement deltaPosition.
- It then performs a
SweepTest to see if a collision occurs along this path.
- If a collision is detected, the player is moved only up to the point of collision (minus a
skinWidth to prevent getting stuck).
- The remaining movement is then projected along the collision normal (sliding effect), and
MovePlayer is recursively called with the slideVector to handle chained collisions (e.g., sliding along a wall into a corner).
Rigidbody2D.collisionDetectionMode set to on the player's Rigidbody2D also helps the engine's built-in collision detection to be more accurate at higher speeds.
This setup provides a robust foundation for a Sonic-like 2D platformer controller with advanced features. Remember to tune the movement and physics variables in the Inspector to match the specific feel you want for your game.