1. 程式人生 > >2D獵寶行動(類掃雷小遊戲)DAY 1

2D獵寶行動(類掃雷小遊戲)DAY 1

1.建立工程和匯入素材

2.製作地圖預製體與詳細面板中自定義顯示特性的使用

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

public class GameManager : MonoBehaviour {

    public static GameManager _instance;

    [Header("元素預製體")]
    [Tooltip("透明背景預製體")]
    public GameObject bgElement;
    [Tooltip("邊界預製體,順序為:")]
    public GameObject[] borderElements;

    [Header("地圖大小")]
    public int w;
    public int h;

    void Awake()
    {
        _instance = this;
    }

}

3.生成地圖的背景與邊界

private void CreateMap()
    {
        Transform bgHolder = GameObject.Find("ElementsHolder/Background").transform;
        for(int i = 0; i < w; i++)
        {
            for(int j = 0; j < h; j++)
            {
                Instantiate(bgElement, new Vector3(i, j, 0), Quaternion.identity, bgHolder);
            }
        }

        for(int i = 0; i < w; i++)
        {
            Instantiate(borderElements[0], new Vector3(i, h + 0.25f, 0), Quaternion.identity, bgHolder);
            Instantiate(borderElements[1], new Vector3(i, -1.25f, 0), Quaternion.identity, bgHolder);
        }

        for(int i = 0; i < h; i++)
        {
            Instantiate(borderElements[2], new Vector3(-1.25f, i, 0), Quaternion.identity, bgHolder);
            Instantiate(borderElements[3], new Vector3(w + 0.25f, i, 0), Quaternion.identity, bgHolder);
        }

        Instantiate(borderElements[4], new Vector3(-1.25f, h + 0.25f, 0), Quaternion.identity, bgHolder);
        Instantiate(borderElements[5], new Vector3(w + 0.25f, h + 0.25f, 0), Quaternion.identity, bgHolder);
        Instantiate(borderElements[6], new Vector3(-1.25f, -1.25f, 0), Quaternion.identity, bgHolder);
        Instantiate(borderElements[7], new Vector3(w + 0.25f, -1.25f, 0), Quaternion.identity, bgHolder);
    }

4.使攝像機對準螢幕中心

 private void ResetCamera()
    {
        Camera.main.orthographicSize = (h + 3) / 2f;
        Camera.main.transform.position = new Vector3((w - 1) / 2f, (h - 1) / 2f, -10);
    }

5.根據遊戲邏輯分析元素的實現方式

分為翻一次,翻兩次以及不翻。

6.製作元素預製體與建立元素基類

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

public class BaseElement : MonoBehaviour {

    public int x;
    public int y;

    public virtual void Awake()
    {
        x = (int)transform.position.x;
        y = (int)transform.position.y;
        name = "(" + x + "," + y + ")";
    }
}