问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Unity开发2D游戏入门教程:贪吃蛇游戏实战

创作时间:
作者:
@小白创作中心

Unity开发2D游戏入门教程:贪吃蛇游戏实战

引用
CSDN
1.
https://blog.csdn.net/weixin_45565886/article/details/144940822

Unity是一款强大的游戏开发引擎,可以用来开发2D和3D游戏。本文将带你从零开始,使用Unity开发一个简单的2D游戏——贪吃蛇。

环境准备

下载Unity

进入Unity官网,选择对应操作系统和版本进行下载。这里推荐下载最新长期支持版(LTS)。

下载.net环境

游戏开发语言使用C#,所以需要准备.net环境。下载地址:https://dotnet.microsoft.com/zh-cn/download

创建项目

我们开发的是2D游戏,这里选择2D游戏模板。

实战开发

场景搭建+实现小蛇跳跃

  1. 在Assets中导入角色与背景图片
  2. 创建Snake物品,create empty

  1. 给这个Snake物品添加一个sprite renderer,将小蛇图片拖入其中,按住shit键可以等比例缩放小蛇
  2. 调整渲染图颜色及物体大小
  3. 点击播放,查看效果
  4. 给Snake这个物品添加Rigidbody 2D重力,让其实现自然坠落
  5. 添加C#脚本代码,实现Snake跳跃操作
using UnityEngine;
public class SnakeController : MonoBehaviour
{
    //每次跳动的高度
    public float jumpForce = 5f;
    private Rigidbody2D rb;
    public GameObject gameOverPanel;
    private bool isGameOver = false;
    public float upperLimit = 1000000000f; // Set this to the top of your screen
    public float lowerLimit = -1000000000f; // Set this to the bottom of your screen
    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    private void Update()
    {
        if (isGameOver) return;
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Jump();
        }
    }
    private void Jump()
    {
        rb.linearVelocity = Vector2.up * jumpForce;
    }
}

创建障碍物+实现物体碰撞

  1. 创建空物品Barrier,在下面分别创建topBarrier、bottomBarrier
  2. 分别给topBarrier、bottomBarrier添加Sprite Renderer,并调整物品页面布局
  3. 添加C#脚本,让障碍物实现向左移动(从视觉上实现小蛇向右移动)
using UnityEngine;
public class BarrierController : MonoBehaviour
{
    public float speed = 2f;
    public float lifetime = 10f;
    private void Start()
    {
        //实现超出范围后,销毁多余的障碍物
        Destroy(gameObject, lifetime);
    }
    private void Update()
    {
        MoveLeft();
    }
    private void MoveLeft()
    {
        //向左移动障碍物
        // Debug.Log("move left....");
        transform.Translate(Vector2.left * speed * Time.deltaTime);
    }
}
  1. 给小蛇、障碍物都添加collider,实现碰撞效果
  2. 解决碰撞后,翻滚问题

脚本实现障碍物自动随机生成

  1. 在Assets目录下新建Prefab文件夹,用于存储我们的复制品
  2. 将Barrier拖到Prefab文件夹中,这样Barrier就成了复制品,然后我们就可以删除场景里的Barrier了
  3. 新建BarrierSpawner物品,并添加BarrierSpawner脚本实现自动生成障碍物
using UnityEngine;
public class BarrierSpawner : MonoBehaviour
{
    public GameObject barrierPrefab;
    public float spawnDelay = 2f;
    public float minSpawnHeight = -2f;
    public float maxSpawnHeight = 2f;
    private void Start()
    {
        //重复调用函数,实现物品复制重复创建
        InvokeRepeating("SpawnBarrier", 0f, spawnDelay);
    }
    private void SpawnBarrier()
    {
        float randomHeight = Random.Range(minSpawnHeight, maxSpawnHeight);
        Vector2 spawnPosition = new Vector2(transform.position.x, randomHeight);
        Instantiate(barrierPrefab, spawnPosition, Quaternion.identity);
    }
}

实现加分机制

  1. Barrier下添加scoreCheck,scoreCheck添加box collider 2d,并勾选Is Trigger
  2. 添加ScoreManager物品,同时添加ScoreManager代码
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI; 
public class ScoreManager : MonoBehaviour
{
    public static int score = 0;
    public Text scoreText;
    private void Update()
    {
        // Update the text field with the current score
        scoreText.text = "Score:" + score.ToString();
    }
    //游戏重新开始,分数清零,重新加载游戏场景
    public void OnRestartButtonClick() // Connect this function to your button's onClick event in the inspector
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        score = 0;
    }
}

实现游戏结束逻辑

  1. Canvas下添加Panel,并调整页面展示位置与大小
  2. GameOverPanel下添加Text与Button,提示游戏结束与重新开始按钮
  3. 隐藏游戏结束页面,当触发碰撞条件时,游戏才结束
private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Barrier"))
    {
        // Game over
        GameOver();
    }
}

private void GameOver()
{
    isGameOver = true; // Add this line
    // Freeze the Snake's motion
    rb.linearVelocity = Vector2.zero;
    if (gameOverPanel != null)
    {
        //展示游戏结束页面
        gameOverPanel.SetActive(true);
    }
}

实现重玩逻辑

给游戏结束页面的[重新开始]按钮绑定事件,点击时,触发游戏重新开始

游戏打包

  1. File - Build Profile
  2. 选择打包参数
  3. 修改压缩参数,改为gzip或不压缩
  4. 点击Build打包游戏,然后选择打包后文件存放位置

游戏上线(itch.io)

itch.io可以算是全球最大的独立游戏平台。它和steam一样,你可以把你的游戏上架到itch上,可以是免费的,也可以让大家捐赠,也可以让大家付费购买。

  1. 注册账号之后,创建项目
  2. 填写游戏基本信息
  3. 保存完后点击项目,改为public,表明游戏公开,然后就可以把体验链接发给其他人体验了

本地运行游玩

打包后的游戏,有两个文件夹(Build、TemplateData),一个文件(index.html)

# 本地运行项目:可以通过python直接起http服务,也可以下载nginx或Tomcat等
# 9999指定运行端口
# --directory 指定unity打包后的路径
python3 -m http.server 9999 --directory /Users/ziyi/Desktop/ZiyiSnakeRun

浏览器访问localhost:9999

全部代码地址(资源文件地址)

Github(欢迎star~):
https://github.com/ziyifast/ziyifast-code_instruction/tree/main/unity-demo/SnakeRun

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号