Unity 创建四个可移动的点,可在四个点围成的空间内生成N行*M列的点位图,并在父物体下生成对应的节点
Unity 创建四个可移动的点,可在四个点围成的空间内生成N行*M列的点位图,并在父物体下生成对应的节点
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateCardSlot : MonoBehaviour
{
[Header("左下")]
public Vector3 point1;
[Header("左上")]
public Vector3 point2;
[Header("右上")]
public Vector3 point3;
[Header("右下")]
public Vector3 point4;
[Header("列")]
public int lineNum = 0;
[Header("行")]
public int columnNum = 0;
[Header("父节点")]
public Transform posParent;
[Header("先行后列")]
public bool foreAndAft = true;//先行后列
}
using System;
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(CreateCardSlot))]
public class CreateCardSlotEditor : Editor
{
CreateCardSlot createCardSlot;
private void OnSceneGUI()
{
createCardSlot = (CreateCardSlot)target;
if (createCardSlot != null)
{
Handles.color = Color.red;
// 创建四个可以移动的点
createCardSlot.point1 = Handles.PositionHandle(createCardSlot.point1, Quaternion.identity);
createCardSlot.point2 = Handles.PositionHandle(createCardSlot.point2, Quaternion.identity);
createCardSlot.point3 = Handles.PositionHandle(createCardSlot.point3, Quaternion.identity);
createCardSlot.point4 = Handles.PositionHandle(createCardSlot.point4, Quaternion.identity);
Handles.DrawSolidDisc(createCardSlot.point1, Vector3.forward, 0.1f);
Handles.DrawSolidDisc(createCardSlot.point2, Vector3.forward, 0.1f);
Handles.DrawSolidDisc(createCardSlot.point3, Vector3.forward, 0.1f);
Handles.DrawSolidDisc(createCardSlot.point4, Vector3.forward, 0.1f);
Sort();
}
}
void Sort()
{
// 通过循环遍历每一行和每一列,计算每个网格单元的中心点的位置
for (int i = 0; i < createCardSlot.columnNum; i++)
{
for (int j = 0; j < createCardSlot.lineNum; j++)
{
Vector2 position = Vector2.zero;
if (!createCardSlot.foreAndAft)
{
//先列后行
position = Vector2.Lerp(
Vector2.Lerp(createCardSlot.point1, createCardSlot.point4, (float)i / (createCardSlot.columnNum - 1)),
Vector2.Lerp(createCardSlot.point2, createCardSlot.point3, (float)i / (createCardSlot.columnNum - 1)),
(float)j / (createCardSlot.lineNum - 1));
}
else
{
//先行后列
position = Vector2.Lerp(
Vector2.Lerp(createCardSlot.point1, createCardSlot.point2, (float)i / (createCardSlot.columnNum - 1)),
Vector2.Lerp(createCardSlot.point4, createCardSlot.point3, (float)i / (createCardSlot.columnNum - 1)),
(float)j / (createCardSlot.lineNum - 1));
}
Handles.color = Color.blue;
// 在每个网格单元的中心点的位置绘制一个点
Handles.DrawSolidDisc(position, Vector3.forward, 0.05f);
// 获取或创建一个新的游戏对象作为子节点
GameObject newNode;
if (createCardSlot.posParent.childCount > i * createCardSlot.lineNum + j)
{
newNode = createCardSlot.posParent.GetChild(i * createCardSlot.lineNum + j).gameObject;
}
else
{
newNode = new GameObject("spawn" + (i * createCardSlot.lineNum + j + 1));
newNode.transform.parent = createCardSlot.posParent;
}
// 更新子节点的位置
newNode.transform.position = position;
}
}
}
}