U
Unity
星辰学院
首页
课程表
章节导览
第 1 课
返回主站
首页
/
第 13 章 · 2D 游戏开发
/
第 205 课
LESSON 205 · 2D 游戏开发
2D 角色控制(移动与跳跃)
2D 角色控制完成。下一课学 2D 物理与刚体。
⏱ 约 15 分钟
📊 难度:
入门
🗂 第 13 章 · 2D 游戏开发
📍 第 205 / 300 课
课程进度
205 / 300
🎯
本节学习目标
实现 2D 移动
实现跳跃
实现朝向翻转
🚀
课程导读
2D 游戏第一件事:角色能左右走、能跳。本课做出核心操作手感。
◆
2D 移动
左右 + 翻转。
【准备】把角色精灵放入场景,加 BoxCollider2D + Rigidbody2D(第 206-207 课),加脚本 PlayerController。
【移动代码】
public float moveSpeed = 5f;
private Rigidbody2D rb;
private SpriteRenderer sr;
void Start() { rb = GetComponent<Rigidbody2D>(); sr = GetComponent<SpriteRenderer>(); }
void Update() {
float h = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(h * moveSpeed, rb.velocity.y);
if (h > 0) sr.flipX = false;
else if (h < 0) sr.flipX = true;
}
【说明】GetAxisRaw 返回 -1/0/1(无平滑);velocity 直接设 X 速度。
【朝向】按移动方向 flipX 翻转精灵。
【注意】2D 刚体用 Rigidbody2D,速度用 rb.velocity(Vector2)。
【测试】左右键移动、精灵跟随翻转。
【优化】跳跃/移动都用 FixedUpdate 里的物理(第 91 课)更稳(velocity 设物理量)。
【注意】别在 Update 里改 rb.velocity 再被物理覆盖,保持一致。
💡
2D 移动 = GetAxisRaw 方向 × 速度 → rb.velocity.x;翻转 = sr.flipX。
◆
2D 跳跃
按下空格跳起。
【跳跃代码】
public float jumpForce = 8f;
public Transform groundCheck; public LayerMask groundLayer;
void Update() {
bool grounded = Physics2D.OverlapCircle(groundCheck.position, 0.1f, groundLayer);
if (Input.GetKeyDown(KeyCode.Space) && grounded) {
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
}
【原理】给刚体一个向上速度(而非 AddForce),跳跃高度可预测。
【落地检测】脚下一个小 Circle 检测地面:
创建子物体 GroundCheck 放脚底;LayerMask 指向“Ground”层(地面设 Ground 层)。
【防连跳】只有 grounded 时才允许跳。
【重力】Rigidbody2D 的 Gravity Scale=1(可调跳跃手感)。
【手感】jumpForce 8-10、moveSpeed 5-8 常见;Velocity 法高度稳定。
【可变跳跃】(进阶)按住跳得更高:松开时若上升中把 velocity.y 减半。
【测试】跑+跳+落地检测正常。
【注意】跳跃要“落地检测”防空中连跳与浮空。
✅
2D 跳跃 = 落地检测(脚底圆圈)+ 直接设向上速度。稳定可控。
⚠
常见错误与排查
⛔
错误:
角色一直“飘”着不落地?
原因:
Rigidbody2D 没启用重力或没有 Collider2D
解决:
确认 Rigidbody2D Gravity Scale>0;有 BoxCollider2D 与地面碰撞。
★
动手练习
课后小任务(做出来才算真的学会)
实现左右移动与翻转
实现跳跃与落地检测
调节速度与跳跃高度
✓
本节小结
2D 角色控制完成。下一课学 2D 物理与刚体。
标记为已完成
完成打卡后,主站会实时更新你的学习进度 🎯
← 上一课
2D 相机设置与像素完美
下一课 →
2D 刚体与物理
↑