Unity是一个强大的游戏引擎,非常适合开发2D和3D游戏。 本文将引导你完成使用Unity制作第一个2D平台游戏的步骤,从创建新项目到角色移动、摄像机跟随、添加敌人和完成关卡。 本教程面向初学者,力求简单易懂。
在开始之前,请确保您已经安装了Unity。 你可以从 Unity 官网下载最新版本,并根据提示安装。Unity官网
强烈推荐使用Unity Hub来管理您的Unity项目和版本。 Unity Hub可以很方便地创建、打开、管理多个Unity项目,并且能够轻松切换不同的Unity版本。
游戏资源包括角色动画、场景背景、地形、敌人图像等。 你可以自己制作资源,也可以从Unity Asset Store或其他资源平台下载。 对于初学者,建议先使用免费资源进行练习。
导入的资源通常会出现在 "Project" 窗口中。
Body Type
为 Kinematic
或 Dynamic
。Kinematic
需要脚本控制移动, Dynamic
允许物理引擎影响角色。Size
和 Offset
属性,使其与角色图像匹配。using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f; // 移动速度
public float jumpForce = 10f; // 跳跃力度
public Transform groundCheck; // 用于检测角色是否在地面上的 Transform
public float groundCheckRadius = 0.2f; // 检测半径
public LayerMask groundLayer; // 地面 Layer
private Rigidbody2D rb; // 刚体组件
private Animator animator; // 动画组件
private bool isGrounded; // 是否在地面上
private float horizontalInput; // 水平输入
void Start()
{
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
void Update()
{
// 获取水平输入
horizontalInput = Input.GetAxis("Horizontal");
// 跳跃
if (Input.GetButtonDown("Jump") && isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
// 设置动画参数
animator.SetFloat("Speed", Mathf.Abs(horizontalInput));
animator.SetBool("IsGrounded", isGrounded);
}
void FixedUpdate()
{
// 检测是否在地面上
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
// 移动
rb.velocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);
//角色朝向
if (horizontalInput > 0)
transform.localScale = new Vector3(1, 1, 1);
else if (horizontalInput < 0)
transform.localScale = new Vector3(-1, 1, 1);
}
// 在 Gizmos 中绘制地面检测圆
void OnDrawGizmosSelected()
{
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(groundCheck.position, groundCheckRadius);
}
}
Move Speed
和 Jump Force
的值,调整角色的移动速度和跳跃力度。Ground Check
的子对象,将其放置在角色脚下,用于检测角色是否在地面上。 将该对象的 Transform 拖拽到 "PlayerController" 脚本的 Ground Check
属性上。Ground Layer
属性中选择 "Ground" Layer。为了让玩家的视角始终跟随角色,需要创建一个摄像机跟随脚本。
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform target; // 要跟随的目标
public float smoothSpeed = 0.125f; // 平滑速度
public Vector3 offset; // 相机偏移量
private Vector3 velocity = Vector3.zero;
void LateUpdate()
{
if (target != null)
{
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.SmoothDamp(transform.position, desiredPosition, ref velocity, smoothSpeed);
transform.position = smoothedPosition;
}
}
}
Target
属性上。 调整 Offset
属性,设置相机与角色的相对位置。 调整 Smooth Speed
属性,控制相机跟随的平滑程度。using UnityEngine;
public class EnemyController : MonoBehaviour
{
public float moveSpeed = 2f; // 移动速度
public float patrolDistance = 5f; // 巡逻距离
private Vector3 startPosition; // 初始位置
private Vector3 currentDirection = Vector3.right; // 初始方向
void Start()
{
startPosition = transform.position;
}
void Update()
{
// 移动
transform.Translate(currentDirection * moveSpeed * Time.deltaTime);
// 检测是否到达巡逻点
if (Vector3.Distance(transform.position, startPosition) > patrolDistance)
{
currentDirection = -currentDirection; // 反向移动
// 反转朝向确保敌人始终面向移动方向
transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
if (currentDirection == Vector3.right)
{
transform.position = startPosition + new Vector3(patrolDistance, 0, 0);
}
else
{
transform.position = startPosition - new Vector3(patrolDistance, 0, 0);
}
}
}
}
处理玩家与敌人之间的碰撞,可以在玩家或敌人脚本中添加 OnCollisionEnter2D
函数。 例如,玩家碰到敌人时,扣除生命值或者游戏结束。
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
// 处理碰撞
Debug.Log("Player hit by enemy!");
// 可增加死亡动画等
Destroy(gameObject); // 摧毁玩家对象
// 也可以调用GameManager的函数来执行游戏结束逻辑
}
}
请确保敌人对象具有 "Enemy" 标签。 (在Inspector窗口顶部的Tag下拉菜单中添加 Tag)。
添加金币、宝石等收集品来增加游戏的乐趣。
创建一个特殊的区域,当玩家到达该区域时,表示完成了关卡。 可以使用 Trigger Collider 2D 进行检测。
Is Trigger
属性勾选上。using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelComplete : MonoBehaviour
{
public string nextSceneName; //下一个场景的名字
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
Debug.Log("Level Complete!");
// 加载下一个场景
SceneManager.LoadScene(nextSceneName);
}
}
}
确保玩家对象具有 "Player" 标签。 (在Inspector窗口顶部的Tag下拉菜单中添加 Tag)。
通过本教程,你已经学习了使用 Unity 制作一个简单的 2D 平台游戏的基础知识。 你可以继续学习更高级的技术,例如:
祝你游戏开发愉快!