Unity3d制作2D游戏飞翔的小鸟(FlappyBird)

目录

一、学习方向

二、制作步骤

1.新建项目

3.设置为精灵模式

4.精灵图像分割

5.场景布局设置

6.录制小鸟飞翔动画

7.构建飞翔的小鸟让其响应

 8.构建UI对象并让其响应

9.构建游戏背景并让其移动

10.障碍生成制作

三、结语


一、学习方向

1.学习设置2D图形

2.搭建2D游戏场景

3.录制小鸟飞翔动画

4.构建飞翔的小鸟让其响应

5.构建UI对象并让其响应

6.构建游戏背景并让其移动

7.障碍生成制作

二、制作步骤

1.新建项目

新建unity2D视图,命名为FlappyBird。(注意:项目名称和存储路径中不要包含中文)

2、导入资源与场景设置

在unity中把我们需要的资源文件Fonts和Sprites拖拽到项目视图文件夹Assets中如下图(选中解压文件夹直接拖动即可)

素材链接:https://pan.baidu.com/s/1au5i39kyDubrhRejYtZT9w?pwd=x46m 
提取码:x46m

3.设置为精灵模式

(1).在工具栏中找到Windows点击,然后在下拉菜单中找到Package Manager 点击弹出如下窗口。

(2).在加号后的菜单中选择Unity  Registry

(3).在Packages选项中找到2D Sprite然后导入(install)即可

4.精灵图像分割

在Assets文件夹中的sprits文件夹中找到我们的BirdHero选中,然后在Inspector(检视视图)中,将Texture Type设置为Sprite(2D and UI),将Sprite Mode设置为Multiple(也就是将单个更改为多个),最后在弹出的窗口中选择Apply(应用)。(如下图所示) 

在点击Apply 之后会弹出新的窗口,在新的窗口最上方菜单栏中选择Slice下拉菜单中点击Slice,这样我们就将BirdHero图片分成了三个小鸟贴图。

关闭这个窗口后,在我们的Sprite文件夹的小鸟素材中就可以看到有三个小鸟素材(如果你的依然显示为BirdHero,不要着急我们只需要点击后面的小三角即可显示。)

5.场景布局设置

(1)将BridHero_01拖到Hierarchy(层级视图)中,重命名为Bird

(2)依次将Grass Thin Sprite和Sky Tile Sprite拖拽到Hierarchy(层级视图)中重命名为Ground和Background

(3)调整图层顺序

选择我们需要调整的图层,在(Inspector)检视视图中找到Order in Layer设置数字,将Bird设置为3,Ground设置为1,BackGround设置为0(效果图如下)

6.录制小鸟飞翔动画

(1)给Bird添加组件Polygen Collider 2D和Rigidbody 2D Component

给Ground添加Box Collider 2D,调整属性,设置参数(如下图),运行一下会发现小鸟会掉落在草地上。

(2)这时的小鸟还不会飞翔,所以我们需要制作小鸟飞翔的动画,步骤如下:

a.选择Bird,在菜单栏中找到Window下拉菜单中的Animation。

b.在弹出的窗口中点击Creat,接着会弹出新的窗口将文件命名为IDLE用来存放资源,然后点击保存即可。(如下图)

c.点击录制按钮,然后点击Add Property,选择Sprite Renderer在下拉菜单中找到Sprite,点击后面的加号。

d.这时候我们需要选中最后一个关键帧将其删除(选中,delete即可)。 

e.选择第一个关键帧,在Inspector(检视视图)中将Sprite设置为BirdHero_0 

f.选择第一个关键帧复制,点击左上角的IDLE下拉菜单中Creat New Clip,命名为Flappy,保存。

在Flappy面板中首先点击录制按钮,然后将我们复制的IDLE的第一个关键帧粘贴在我们Flappy中,在Inspector(检视视图)中找到Sprite为BirdHero_1。

g.按照步骤f,新建一个Clip命名为DIE,点击录制按钮,复制第一个关键帧,然后更改Sprite为BirdHero_2。到这一步我们就完成了小鸟飞翔的录制。点击关闭Animation,在弹出的窗口保存为Animations。(如果没有弹出系统会默认保存在Assets文件中)

(3)双击Bird Controller进入Animator 面板中

 选择IDLE右击选择Make Transition

将IDLRE和另外两个(DIE和Flappy)链接起来,然后选择Flappy右键选择Make Transition制作一条从Flappy到IDLE 的线

在我们的Animator 面板菜单栏中找到Parameters在下面创建两个Trigger分别命名为Flappy和Die 

选择从IDLE到DIE的线,在Inspector(检视视图)中,取消勾选Has Exit Time,在下面Conditions中点击加号选择Die 

选择从IDLE到Flappy的线,在Inspector(检视视图)中,取消勾选Has Exit Time,在下面Conditions中点击加号选择Flappy(如下图所示)。 

从Flappy到IDLE这条线,我们希望在Flappy播放完后直接切换回IDLE,因此不需要取消Has Exit Time的勾选,也不需要设置Conditions,所以这条线就不用管了。

7.构建飞翔的小鸟让其响应

回到Scene视口,首先我们在Assets中新建一个文件夹:点击Assets在空白区域右击选择Create在下拉列表中找到Folder就会创建出一个新的文件夹,这个文件夹主要存放我们的脚本

双击打开我们的Scripts文件夹,然后空白区域右键选择Create下拉列表中的C# Script,然后重命名为Bird,然后将我们的脚本左击不放拖拽到Bird上面

双击打开脚本,进行编译,这一步是鼠标点击屏幕小鸟向上飞翔,Ctrl+s保存脚本然后回到我们的Unity中,这时点击运行我们的游戏,就实现了小鸟向上飞翔

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bird : MonoBehaviour
{

    public float upperForce = 250f;         // the force add to bird when it flappy.

    private Rigidbody2D rb2d;               // the rigidbody 2d component
    private Animator animator;              // the animator component
    private bool isDead = false;            // mark if bird is dead.

    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0) && !isDead)
        {      // check input and bird's status
            rb2d.velocity = Vector2.zero;
            rb2d.AddForce(new Vector2(0, upperForce));    // add a upper force
            animator.SetTrigger("Flappy");                 // change current animation clip to flappy
        }
    }

    void OnCollisionEnter2D()
    {
        rb2d.velocity = Vector2.zero;
        isDead = true;
        animator.SetTrigger("Die");                        // change current animation clip to Die
        
    }


}

 8.构建UI对象并让其响应

(1)在Hierarchy(层级视图)中右键找到UI在下拉列表中找到legacy(旧版)下拉列表选择Text点击创建,重命名为Score Text用来记录分数

(2)选中Score Text,更改Text属性为Score:0,将字体改为LuckiesGuy,设置字体大小Font Size为22,将Alignment属性选择中间两个将字体居中,把字体颜色更改为白色。

(3)选中Score Text,Ctrl+d拷贝两份,分别重命名为GameOverText和RestartText,参照上一步调整字体大小及位置(记得更改Text属性哦),将RestartText拖拽到GameOverText上,让RestartText成为GameOverText的子对象。效果图如下

(4)在Hierarchy视图中右键创建空物体CreateEmpty重命名为GameManager

(5)在Scripts文件夹中创建脚本,右键>create>C# script,重命名为GameManager,然后将其拖拽到我们创建的空物体GameManager上。

(6)双击打开GameManager脚本,进行编辑,主要是更新得分和小鸟死后弹出Game Over UI更新画面Ctrl+s保存,回到unity

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;

public class GameManager : MonoBehaviour
{

    public static GameManager instance;             // single instance

    public GameObject gameOverText;                 // game over UI
    public Text scoreText;                          // score text
    public Button playBtn;
    public GameObject logo;

    private bool gameOver = false;                  // mark current game status
    private int score = 0;                          // store score.


    void Awake()
    {
        if (instance == null)
        {                     // set single instance
            instance = this;
        }
        else if (instance != null)
        {
            Destroy(gameObject);
        }
    }

    void Update()
    {
        if (gameOver == true && Input.GetMouseButtonDown(0))
        {         // if gameover and click the picture, restart the game.
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }
    }

    public void AddScore()                          // when the bird cross a obstacle, add score.
    {
        if (gameOver)
            return;

        score += 1;
        scoreText.text = "Score: " + score.ToString();
    }

    public void GameOver()                          // game over function.
    {
        gameOverText.SetActive(true);
        gameOver = true;
       
    }

   

}

(7)双击打开Bird脚本,添加GameOver方法GameManager.instance.GameOver(),添加在 void OnCollisionEnter2D中,Ctrl+S保存,回到unity。

 void OnCollisionEnter2D()
    {
        rb2d.velocity = Vector2.zero;
        isDead = true;
        animator.SetTrigger("Die");                        // change current animation clip to Die
        GameManager.instance.GameOver();
    }

(8)在Hirarchy视图中添加一个Image(图片)重命名为logo,和一个Botton(按钮)重命名为playBtn

选中logo在Inspector视图中更改Source Image属性为标题

选中 playBtn,删除下面自带的Text(Legacy),在Inspector视图中更改Source Image属性为btnPlay

调整playBtn 和logo位置及大小效果图如下

(9)选中Hierarchy视图中的GameManager,将Score Text、Game Over、logo 、playBtn 拖拽到Inspector相应的位置。

选中GameOver 取消勾选Active。

(10)创建一个脚本命名为UIManager,将这个脚本拖拽到logo 和playBtn 上

双击打开我们的GameManager脚本,在代码最后面添加Play的定义指令(添加在GameOver后),这样我们就可以在UIManager脚本中调用Ctrl+s保存

 public void GameOver()                          // game over function.
    {
        gameOverText.SetActive(true);
        gameOver = true;
        //UIManager.Instance.ShowUI();

    }
    internal void Play()
    {
        throw new NotImplementedException();
    }

接下开打开我们的UIManager脚本进行编辑,Ctrl+s保存,将此脚本拖分别拽到playBtn和logo上

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
public class UIManager : MonoBehaviour
{
    public Button playBtn;
    public GameObject logo;
    public static UIManager Instance;
    // Use this for initialization
    void Awake()
    {
        Instance = this;
    }
    void Start()
    {
        playBtn.onClick.AddListener(onPlay);
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void onPlay()
    {
        playBtn.gameObject.SetActive(false);
        logo.SetActive(false);
        GameManager.instance.Play();
    }

    public void ShowUI()
    {
        playBtn.gameObject.SetActive(true);
    }
}

选中logo在Inspector中修改UIManager 属性,如下图所示 

9.构建游戏背景并让其移动

(1)给Ground添加一个Rigidbody  2D的组件,将Body Type属性更改为Kinematic(因为是通过脚本来移动,而不是用物理系统来完成移动)

在Scripts文件夹中创建新的脚本重命名为ScorllingObject,Ctrl+S将其赋予到Ground上

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScrollingObject : MonoBehaviour
{

    public float scrollSpeed = -2f;         // object scroll speed.

    private Rigidbody2D rb2d;

    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
        rb2d.velocity = new Vector2(scrollSpeed, 0);
    }

    void Update()
    {
        if (GameManager.instance.gameOver == true)
        {
            rb2d.velocity = Vector2.zero;
        }
    }

}

(2)新建一个c#脚本重命名为RepeatingBackground,打开编辑脚本,Ctrl+s保存脚本将脚本拖拽到Ground上。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RepeatingBackground : MonoBehaviour
{

    private BoxCollider2D groundCollider;
    private float groundHorizontalLength;               // store background's width.

    void Start()
    {
        groundCollider = GetComponent<BoxCollider2D>();
        groundHorizontalLength = groundCollider.size.x;             // get background's width;
    }

    void Update()
    {
        if (transform.position.x < -groundHorizontalLength)
        {       // when it move out of screen, reset it's position.
            RepositionBackground();
        }
    }

    void RepositionBackground()
    {
        Vector2 groundOffset = new Vector2(groundHorizontalLength * 2f, 0);
        transform.position = (Vector2)transform.position + groundOffset;        // reset position
    }

}

(3)将Background拖拽到Ground上,让其成为Ground的一个子对象,新建一个空物体重命名为Bg,将Ground拖拽到Bg上让他成为Bg的子对象,调整Ground的位置,复制一份Groung,效果图如下 。

10.障碍生成制作

(1)将ColumnSprite拖拽到Hierarchy中,为其添加一个Box Collider 2D Component组件调整大小修改属性参数,如下图所示 

 (2)复制一份ColumnSprite,旋转,调整位置如下

(3)创建一个空物体命名为Column,将两个ColumnSprite拖拽到空物体上,给空物体添加RigidBody 2D组件,设置Type为Kinematic,添加一个Box Collider 2D组件,勾选Is Trigger,调整属性参数,如下图所示

 (4)将ScrollingObject脚本拖拽到Column上,然后新建脚本命名为ColumnCtrl+s保存,然后将脚本拖拽到Column上。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Column : MonoBehaviour
{

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.GetComponent<Bird>() != null)
        {
            GameManager.instance.AddScore();
        }
    }
}

(5)在Project中新建文件夹命名为Prefabds,将空物体Column拖拽到文件夹中让其成为预制件,这时你会发现Column变成了蓝色。 

(6)新建一个脚本命名为ColumnPool,用于管理Column,将此脚本拖拽到GameManager上然后将预制文件夹中的Column拖拽到Column Prefab中如下图所示。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ColumnsPool : MonoBehaviour
{

    public GameObject columnPrefab;         // column prefab
    public int poolSize = 5;                // max size of pool
    public float spawnRate = 4.5f;          // spawn rate
    public float columnYMin = -1.45f;       // column's min y
    public float columnYMax = 2.8f;         // column's max y

    private GameObject[] columns;           // column pool
    private Vector2 startSpawnPos = new Vector2(13f, 0f);  // origin start spawn position.
    private float spawnXPosition = 10f;     // column's x not change.
    private float lastSpawnTime = 0;        // record the last spawn time.
    private int currentIndex = 0;           // current column's index in pool

    void Start()
    {
        columns = new GameObject[poolSize];     // init columns pool
        for (int i = 0; i < poolSize; i++)
        {
            columns[i] = (GameObject)Instantiate(columnPrefab, startSpawnPos, Quaternion.identity);
            columns[i].SetActive(false);
        }
    }

    void Update()
    {
        if (Time.time - spawnRate > lastSpawnTime)
        {        // after spawnRate time, reset a column's position
            lastSpawnTime = Time.time;
            float columnY = Random.Range(columnYMin, columnYMax);  // get a random y.
            columns[currentIndex].transform.position = new Vector2(spawnXPosition, columnY);  // reset position
            columns[currentIndex].SetActive(true);        // active column
            currentIndex++;                                 // turn to next column.

            if (currentIndex >= poolSize)
            {                 // check overflow
                currentIndex = 0;
            }
        }
    }

}

(7)删除Hierarachy中的 Column,运行游戏测试一下即可。

(8)当你运行的时候发现,你的游戏界面是这样的,那么我们只需要修改游戏场景的大小即可

打开我们的游戏视图,点击Free Aspect下拉列表找到+号,创建一个320×480场景大小即可 

最后你就会得到这样的视图

三、结语

        如果你想让你的游戏更加有趣可以为他添加游戏音效等等,那么本次游戏制作就到此结束啦,不要忘了点赞加关注哦~

注意:如果发现本文章有侵权内容,可以随时联系作者本人,本人将即使撤回进行修改。

  • 18
    点赞
  • 76
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
当然可以!以下是一个简单的Java小游戏飞翔小鸟的代码示例: ```java import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class BirdGame extends JFrame implements KeyListener { private int birdY = 250; // 小鸟的初始位置 private int speed = 0; // 小鸟的初始速度 public BirdGame() { setTitle("飞翔小鸟"); setSize(800, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); setVisible(true); addKeyListener(this); } public void paint(Graphics g) { super.paint(g); g.fillRect(100, birdY, 20, 20); // 绘制小鸟 } public void keyTyped(KeyEvent e) {} public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SPACE) { speed = -10; // 按下空格键,小鸟向上飞行 } } public void keyReleased(KeyEvent e) {} public void birdMove() { birdY += speed; // 更新小鸟的位置 speed += 1; // 更新小鸟的速度 if (birdY >= 530) { birdY = 530; // 小鸟触底时停止下落 } repaint(); // 重绘界面 } public static void main(String[] args) { BirdGame game = new BirdGame(); while (true) { game.birdMove(); try { Thread.sleep(20); // 控制小鸟的速度 } catch (InterruptedException e) { e.printStackTrace(); } } } } ``` 这个代码示例实现了一个简单的飞翔小鸟游戏。通过按下空格键,小鸟会向上飞行,松开空格键后小鸟会自由下落。小鸟的位置和速度会不断更新,并通过重绘界面来实现动画效果。
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值