十三UI和关卡

使用Unity3D的UI功能来创建UI。

13.1创建UI

13.1.1Canvas

首先创建Canvas来方式UI所需组件,方法:点击窗口GameObject/UI/Canvas如图:

Unity文字打怪游戏 unity2d文字游戏教程_Image


13.1.2Image

创建一个Image组件GameObject/UI/Image。系统会自动创建Image并设置为canvas的子对象。切换Scenc窗口。鼠标中键拉远镜头。直到image出现在窗口中。如图:

Unity文字打怪游戏 unity2d文字游戏教程_Unity文字打怪游戏_02


设置Ancher切换Inspector窗口。点击

Unity文字打怪游戏 unity2d文字游戏教程_unity3d_03

按住键盘Alt键同时悬着Anchor Presets窗口右下角的Stretch。

Unity文字打怪游戏 unity2d文字游戏教程_unity3d_04


设置Image (Script)/Color为黑色

Unity文字打怪游戏 unity2d文字游戏教程_Image_05


修改Image的名称为LevelImage即可。

13.1.3Text

创建Text来显示关卡数,首先选定LevelImage,创建GameObject/UI/Text。系统自动一个Text并设置为Canvas子组件。修改名称为LevelText。

修改Anchor为屏幕中心。方法参考Image。如图:

Unity文字打怪游戏 unity2d文字游戏教程_Unity文字打怪游戏_06


设置Text(Script)/Color = White

设置Text(Script)/Charactor / Font Size = 12 如图:

Unity文字打怪游戏 unity2d文字游戏教程_Image_07


发现窗口中的文字显示不正常,这是由于字体过大,显示区域过小造成的。

设置Text(Script)/Paragraph/Horzontial Overflow = overflow

设置Text(Script)/Paragraph/Vertial Overflow = overflow

Unity文字打怪游戏 unity2d文字游戏教程_UI_08


设置Text(Script)/ Charactor /Alignment = center,Middle

设置Text(Script)/ Charactor /Font = PressStart2P-Regular 位于Project/Asserts/Font下面。

设置Text(Script)/Text = “Day 1”

Unity文字打怪游戏 unity2d文字游戏教程_unity3d_09


设置LevelText为LevelImage的子组件。方便控制。

Unity文字打怪游戏 unity2d文字游戏教程_Text_10


同样方法创建Food参数如下:

Anchor = bottom-center 
 Text = “Food: 100” 
 Font = PressStart2P-Regular 
 Font Size = 24 
 Alignment = center,Middle 
 Horzontial Overflow = overflow 
 Vertial Overflow = overflow 
 Color = white

由于FoodText在游戏运行时候的显示,所以需要把FoodText设置在LevelImage更深的一层。方式:设置FoodText移动到Canvas下面并且LevelImage上面。此时在窗口中看不到FoodText。切换到Inspector窗口,把LevelImage对象的设置成不可见。(取消选中即可)如图:

Unity文字打怪游戏 unity2d文字游戏教程_Text_11


就可以看见FoodText了。如图:

Unity文字打怪游戏 unity2d文字游戏教程_Image_12


移动FoodText向上一些。设置

Pos Y = 0

Anchors/ Min Y = 0.05

Anchors/ Max Y = 0.05

Unity文字打怪游戏 unity2d文字游戏教程_Image_13


13.2修改脚本

修改GameManager。cs如下

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class GameManager : MonoBehaviour 
{
    //从新开始关卡的延迟
    public float  startLevelDelay = 2f;
    //延迟
    public float turnDelay = 0.1f;
    //敌人
    private List<Enemy> enemies;
    //敌人是否移动
    private bool enemiesMoving;
    public static GameManager instance = null;
    //关卡管理器脚本
    public BoardManager boardScript;
    //初始关卡数
    private int level = 1;
    public int playerFoodPoints = 100;
    [HideInInspector]
    public bool playersTurn = true;

    private Text levelText ;
    private GameObject levelImage;
    private bool doingSetup;

    void Awake () 
    {
        if (instance == null)
            instance = this;
        else
            Destroy(instance);
        DontDestroyOnLoad(gameObject);
        //初始化敌人信息
        enemies = new List<Enemy>();
        //初始化关卡脚本
        boardScript = GetComponent<BoardManager>();
        //初始化游戏
        InitGame();
    }
    //Unity内置API在每个场景加载后调用
    private void OnLevelWasLoaded(int index)
    {
        level ++;
        InitGame();
    }

    public void GameOver()
    {
        levelText.text  =" After "+level +" daies, you starved.";
        levelImage.SetActive(true);
        enabled =false;
    }
    //初始化游戏
    void InitGame()
    {
        doingSetup = true;
        levelImage = GameObject.Find("LevelImage");
        levelText = GameObject.Find("LevelText").GetComponent<Text>();
        levelText.text = "Day " + level;
        levelImage.SetActive(true);
        Invoke("HideLevelImage",startLevelDelay);
        //清空上一关敌人信息
        enemies.Clear();
        boardScript.SetupScene(level);
    }
    IEnumerator MoveEnemies()
    {
        enemiesMoving = true;
        yield return new WaitForSeconds(turnDelay);
        if(enemies.Count == 0)
        {
            yield return new WaitForSeconds(turnDelay);
        }
        for(int i=0;i<enemies.Count;i++)
        {
            enemies[i].EnemyMove();
            yield return new WaitForSeconds(enemies[i].moveTime);
        }
        playersTurn = true;
        enemiesMoving = false;
    }
    void Update () 
    {
        if(playersTurn || enemiesMoving ||doingSetup)
            return;
        StartCoroutine(MoveEnemies());
    }
    public void AddEnemyToList(Enemy script)
    {
        enemies.Add(script);
    }
}

修改Player。cs代码如下:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Player : MovingObject
{
    //对内墙的破坏力
    public int wallDamage = 1;
    //食物增加生命
    public int pointsPerFood = 10;
    //苏打增加生命
    public int pointsPerSoda = 20;
    //重启延迟时间
    public float restartLevelDelay = 1f;
    //Player动画
    private Animator animator;
    //当前生命值
    private int food ;

    public Text foodText;

    protected override void Start () 
    {
        animator = GetComponent<Animator>();
        food = GameManager.instance.playerFoodPoints;
        foodText.text = "Food: "+food;
        base.Start();
    }
    void Update () 
    {
        if(!GameManager.instance.playersTurn)
            return ;
        //键盘输入,控制角色移动。
        int horizontal = 0;
        int vertical = 0 ;
        horizontal = (int)Input.GetAxisRaw("Horizontal");
        vertical = (int)Input.GetAxisRaw("Vertical");
        if(horizontal!=0)
            vertical = 0;
        if(horizontal!=0 || vertical!=0)
            AttemptMove<Wall>(horizontal,vertical);
    }
    //内置函数
    private void OnDisable()
    {
        GameManager.instance.playerFoodPoints = food;
    }
    protected override void AttemptMove<T>(int xDir,int yDir)
    {
        //没移动一次食物减少1
        food--;
        foodText.text = "Food: "+food;
        base.AttemptMove<T>(xDir,yDir);
        GameManager.instance.playersTurn =false;
    }
    //检查是否游戏结束
    private void CheckIfGameOver()
    {
        //当前生命低于0游戏结束
        if(food <= 0 )
        {
            GameManager.instance.GameOver();
        }
    }
    //碰撞内墙
    protected override void OnCantMove<T>(T component)
    {
        Wall hitWall = component as Wall;
        //破坏内墙
        hitWall.DamageWall(wallDamage);
        //出发PlayerChop触发器
        animator.SetTrigger("PlayerChop");
    }
    //主角移动套exit的时候,加载下一关
    private void Restart()
    {
        Application.LoadLevel(Application.loadedLevel);
    }
    //主角被敌人攻击的时候损失生命值
    public void LoseFood(int loss)
    {
        //出发PlayerHit触发器
        animator.SetTrigger("PlayerHit");
        food -= loss;
        foodText.text = "-" + loss + "Food: "+food;
        CheckIfGameOver();
    }
    //检查碰撞,exit,food,soda
    private void OnTriggerEnter2D(Collider2D other)
    {
        //主角移动到出口
        if(other.tag == "Exit")
        {
            Invoke("Restart",restartLevelDelay);
            enabled = false;
        }
        //吃掉食物
        else if(other.tag == "Food")
        {
            food += pointsPerFood;
            foodText.text = "+" + pointsPerFood + " Food: "+food;
            other.gameObject.SetActive(false);
        }
        //喝掉苏打汽水
        else if(other.tag == "Soda")
        {
            food += pointsPerSoda;
            foodText.text = "+" + pointsPerSoda + "Food: "+food;
            other.gameObject.SetActive(false);
        }
    }
}

修改Player预制体的Player脚本的FoodText属性为Canvas/FoodText