2D 游戏开发
Unity 强大的 2D 游戏开发功能让你可以轻松创建精美的 2D 游戏。本章将介绍 2D 开发的核心概念和技术。
2D 与 3D 模式
Unity 支持 2D 和 3D 开发模式,创建项目时需要选择:
- 2D 模式:默认使用正交相机,导入的图片自动设置为 Sprite
- 3D 模式:默认使用透视相机,需要手动配置 2D 功能
模式切换
在编辑器中可以通过 Edit > Project Settings > Editor > Default Behavior Mode 切换默认模式。
Sprite(精灵)
Sprite 是 2D 游戏中的基本图像元素。
导入图片为 Sprite
- 将图片拖入 Project 窗口
- 选中图片,在 Inspector 中设置:
- Texture Type:
Sprite (2D and UI) - Sprite Mode:
Single- 单张图片Multiple- 图集(需要切割)Polygon- 多边形
- Texture Type:
Sprite 属性设置
| 属性 | 说明 |
|---|---|
| Pixels Per Unit | 每单位像素数,决定 Sprite 在世界中的大小 |
| Pivot | 锚点位置,影响旋转和缩放中心 |
| Generate Physics Shape | 自动生成物理碰撞形状 |
Sprite 编辑器
选中 Sprite 后点击 Sprite Editor 按钮:
- 切割图集:自动或手动切割 Sprite Sheet
- 设置锚点:调整 Sprite 的中心点
- 编辑边框:设置 9-slice 拉伸区域
Sprite Editor 功能:
├── Slice - 自动/手动切割
├── Trim - 裁剪空白区域
├── Pivot - 设置锚点
├── Border - 9-slice 边框
└── Physics Shape - 物理形状
Sprite Renderer(精灵渲染器)
Sprite Renderer 组件负责在场景中显示 Sprite。
主要属性
// 代码示例:动态修改 Sprite
public class SpriteController : MonoBehaviour
{
public SpriteRenderer spriteRenderer;
public Sprite newSprite;
void Start()
{
// 更换 Sprite
spriteRenderer.sprite = newSprite;
// 修改颜色
spriteRenderer.color = Color.red;
// 翻转
spriteRenderer.flipX = true;
}
}
| 属性 | 说明 |
|---|---|
| Sprite | 要显示的 Sprite 资源 |
| Color | 着色颜色(可用于受伤闪烁效果) |
| Flip X/Y | 水平/垂直翻转 |
| Sorting Layer | 排序层级,控制渲染顺序 |
| Order in Layer | 同层内的渲染顺序 |
排序层级(Sorting Layer)
控制 2D 元素的渲染顺序:
- Edit > Project Settings > Tags and Layers > Sorting Layers
- 添加自定义层级:Background, Midground, Foreground, UI
- 层级越高,渲染越靠前
2D 物理系统
Rigidbody 2D
2D 刚体组件,控制物体的物理行为:
| Body Type | 说明 |
|---|---|
| Dynamic | 完全物理模拟,受力和重力影响 |
| Kinematic | 不受力影响,通过代码控制运动 |
| Static | 静止不动,如地面和墙壁 |
public class PlayerMovement2D : MonoBehaviour
{
public Rigidbody2D rb;
public float moveSpeed = 5f;
public float jumpForce = 10f;
void Update()
{
// 水平移动
float moveInput = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y);
// 跳跃
if (Input.GetButtonDown("Jump"))
{
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
}
}
Collider 2D
2D 碰撞器类型:
- Box Collider 2D:矩形碰撞
- Circle Collider 2D:圆形碰撞
- Polygon Collider 2D:多边形碰撞
- Edge Collider 2D:边缘碰撞(用于地形)
- Capsule Collider 2D:胶囊形碰撞
碰撞检测
public class CollisionDetector2D : MonoBehaviour
{
// 碰撞开始
void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("碰撞对象:" + collision.gameObject.name);
}
// 持续碰撞
void OnCollisionStay2D(Collision2D collision)
{
// 处理持续碰撞
}
// 碰撞结束
void OnCollisionExit2D(Collision2D collision)
{
Debug.Log("离开碰撞:" + collision.gameObject.name);
}
// 触发器检测
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Coin"))
{
Destroy(other.gameObject);
// 增加分数
}
}
}
Tilemap(瓦片地图)
Tilemap 是创建 2D 关卡的重要工具。
创建 Tilemap
- Hierarchy > 2D Object > Tilemap > Rectangular
- 系统自动创建 Grid 和 Tilemap
Tile Palette(瓦片调色板)
- Window > 2D > Tile Palette
- 创建新的 Palette
- 将 Sprite 拖入 Palette 生成 Tile
- 使用画笔工具绘制地图
常用工具
| 工具 | 快捷键 | 功能 |
|---|---|---|
| Select | S | 选择 Tile |
| Move | M | 移动 Tile |
| Brush | B | 绘制 Tile |
| Box Fill | U | 矩形填充 |
| Flood Fill | G | 洪水填充 |
| Eraser | E | 擦除 |
多个 Tilemap 层级
Grid
├── Tilemap_Ground (地面层)
├── Tilemap_Decoration (装饰层)
├── Tilemap_Foreground (前景层)
└── Tilemap_Collision (碰撞层,通常不渲染)
Tilemap Collider 2D
为 Tilemap 添加碰撞:
- 选中 Tilemap 对象
- 添加 Tilemap Collider 2D 组件
- 可选:添加 Composite Collider 2D 合并碰撞体
- 勾选 Used By Composite 优化性能
2D 动画
Sprite Animation
- 选中多个 Sprite
- 拖入 Hierarchy,自动创建动画
- 或在 Animation 窗口创建动画
Animator 2D
public class PlayerAnimation2D : MonoBehaviour
{
public Animator animator;
public Rigidbody2D rb;
void Update()
{
// 设置动画参数
animator.SetFloat("Speed", Mathf.Abs(rb.velocity.x));
animator.SetBool("IsGrounded", IsGrounded());
animator.SetTrigger("Jump");
}
}
2D 光照(URP)
使用 Universal Render Pipeline 获得 2D 光照效果:
- Window > Package Manager 安装 URP
- Assets > Create > Rendering > URP Asset (with 2D Renderer)
- Edit > Project Settings > Graphics 设置 Scriptable Render Pipeline
- 添加 Light 2D 组件
2D 光源类型
- Freeform:自由形状光源
- Sprite:使用 Sprite 作为光源形状
- Point:点光源
- Global:全局光照
相机控制
Cinemachine 2D
- Package Manager 安装 Cinemachine
- Cinemachine > Create 2D Camera
- 设置 Follow 目标
// 简单的相机跟随
public class CameraFollow2D : MonoBehaviour
{
public Transform target;
public float smoothSpeed = 0.125f;
public Vector3 offset;
void LateUpdate()
{
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
}
}
实践:简单的 2D 平台跳跃游戏
玩家控制器
public class PlatformerPlayer : MonoBehaviour
{
[Header("移动")]
public float moveSpeed = 5f;
public float jumpForce = 12f;
[Header("地面检测")]
public Transform groundCheck;
public float groundCheckRadius = 0.2f;
public LayerMask groundLayer;
private Rigidbody2D rb;
private Animator animator;
private bool isGrounded;
private float moveInput;
void Start()
{
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
void Update()
{
// 地面检测
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
// 水平输入
moveInput = Input.GetAxisRaw("Horizontal");
// 跳跃
if (Input.GetButtonDown("Jump") && isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
animator.SetTrigger("Jump");
}
// 更新动画
animator.SetFloat("Speed", Mathf.Abs(moveInput));
animator.SetBool("IsGrounded", isGrounded);
// 翻转角色
if (moveInput != 0)
{
transform.localScale = new Vector3(Mathf.Sign(moveInput), 1, 1);
}
}
void FixedUpdate()
{
// 应用移动
rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y);
}
}
下一步
掌握 2D 开发基础后,你可以: