unity 正六边形网格绘制(精简版)-代码可直接复用

6 篇文章 1 订阅

本文旨在六边形网格精简版绘制,可以此为基础实现具体的功能
六边形网格是用一个二维数组进行存放,能最大程度的对应正方形网格以及替换,具体实现如下:
在这里插入图片描述

面板部分

在这里插入图片描述
其中的Text为预制体,用于显示对应的格子下标

HexagonModal类

using UnityEngine;
public class HexagonModal
{
	public const float outerRadius = 10f;   //外圈半径
	public const float innerRadius = outerRadius * 0.866025404f;

	public static Vector3[] corners = {
		new Vector3(0f, 0f, outerRadius),
		new Vector3(innerRadius, 0f, 0.5f * outerRadius),
		new Vector3(innerRadius, 0f, -0.5f * outerRadius),
		new Vector3(0f, 0f, -outerRadius),
		new Vector3(-innerRadius, 0f, -0.5f * outerRadius),
		new Vector3(-innerRadius, 0f, 0.5f * outerRadius),
		new Vector3(0f, 0f, outerRadius)
	};
}

HexGridCell类

using UnityEngine;

public class HexGridCell : MonoBehaviour
{
    public HexGrid grid; //隶属问题
    public Vector3 CenterPos;
    public HexagonModal Cell;
}

HexGrid类

using UnityEngine;
using UnityEngine.UI;

public class HexGrid : MonoBehaviour
{

    public HexGridCell[,] cells;
    public int Width=1;
    public int Height=1;
    public Canvas CanvasShow;
    public Text TextPrefab;


    private void Start()
    {
        cells = new HexGridCell[Width, Height];
        CreateCell();
    }

    /// <summary>
    /// 创建网格
    /// </summary>
    void CreateCell()
    {
        for (int i = 0; i < Width; i++)
        {
            for (int j = 0; j < Height; j++)
            {
                HexGridCell cell = new HexGridCell();
                Vector3 position;
                position .x= (j + (i%2) * 0.5f) * (HexagonModal.innerRadius * 2f);
                position .y = 0;
                position .z = i * (HexagonModal.outerRadius * 1.5f);
                cell.CenterPos = position;
                cells[i, j] = cell;

                #region 显示格子下标
                TextPrefab.text = i + "," + j;
                Quaternion q1 = new Quaternion();
                q1.eulerAngles = new Vector3(90, 0, 0);
                Text go= Instantiate(TextPrefab, cell.CenterPos,q1);
                go.transform.SetParent(CanvasShow.transform);

                for (int k = 0; k <= 6; k++)
                {
                    Debug.DrawLine(cells[i, j].CenterPos + HexagonModal.corners[k], cells[i, j].CenterPos + HexagonModal.corners[(k + 1) % 7], Color.green, 20000);
                }
                #endregion
            }
        }
    }
}

参考 https://www.redblobgames.com/grids/hexagons/ (此文对正六边形网格系统有较丰富的介绍以及应用)
本文为自行理解完成以及分享,如有不妥之处,欢迎指正。

  • 0
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MelanceXin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值