
利申:自學Unity,非專業教學,如果有錯誤歡迎補充指正

開始前俾大家睇下啲例子先:
Mindusty

Core Keeper

-----------------------------------------------------
首先開個新2D Project,我用嘅Unity版本係2022.2.7f1

首先我哋要用Grid將地圖割開一格格先(Grid Cell),加個Empty GameObject再撳Add Component加Grid (2D同3D都可以用Grid)

Grid有4個Properties可以set
1) Cell Size: 每一格嘅大小
2) Cell Gap: 每一格嘅間隔
3) Cell Layout: 每一格嘅形狀,有4款可以揀:
Rectangle

Hexagon

Isometric 同埋 Isometric Z as Y

4) Cell Swizzle: 將XYZ重新排序做其中一個選項
-----------------------------------------------------
之後要將mouse postion反映返落去grid cell到,create一個新script:
using UnityEngine;
public class InputManager : MonoBehaviour
{
//攞Grid Component
[SerializeField]private Grid grid;
//顯示Mouse目前所在位置
[SerializeField]private GameObject mouseIndicator;
//攞Main Camera
private Camera mainCamera;
//Save低Mouse位置
private Vector2 mousePosition;
private void Start()
{
//Camera.main會係套用MainCamera Tag嘅Camera
mainCamera = Camera.main;
}
private void Update()
{
UpdateMouseIndicator();
}
private void UpdateMouseIndicator(){
//攞Mouse目前所在位置
mousePosition = mainCamera.ScreenToWorldPoint(Input.mousePosition);
//更新mouseIndicator位置
mouseIndicator.transform.position = grid.WorldToCell(mousePosition);
}
}
[SerializeField]: 正常private field唔會喺Inspector顯示,加呢句就可以強制serialize個private field
mouseIndicator: 一個要嚟顯示目前所在位置嘅GameObject


Camera.main: 用緊MainCamera Tag嘅Camera

ScreenToWorldPoint: 將座標從Screen Position轉換為World Position
WorldToCell: 將座標從World Position轉換為Cell Position,咁就可以將GameObject正確放喺Cell上面
-----------------------------------------------------
Hierarchy嘅樣

Input Manager

Grid System

-----------------------------------------------------
完成效果

之後會整埋鏡頭移動先可加建築系統

-----------------------------------------------------
詳細嘅document:
Grid
https://docs.unity3d.com/2022.2/Documentation/ScriptReference/Grid.html
SerializeField
https://docs.unity3d.com/2022.2/Documentation/ScriptReference/SerializeField.html
Camera.main
https://docs.unity3d.com/2022.2/Documentation/ScriptReference/Camera-main.html
ScreenToWorldPoint
https://docs.unity3d.com/2022.2/Documentation/ScriptReference/Camera.ScreenToWorldPoint.html
WorldToCell
https://docs.unity3d.com/2022.2/Documentation/ScriptReference/GridLayout.WorldToCell.html