分为两个部分,一个是获取野怪生成点的数据,二是生成野怪。
获取野怪生成点的数据
(1)通过放置物体来定位我们想要让其生成的位置,并且附加上一个脚本用来在编辑模式下显示物体。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class SpawnPoint : MonoBehaviour
{
Mesh mesh = null;
public int ID;
// Start is called before the first frame update
void Start()
{
this.mesh = this.GetComponent<MeshFilter>().sharedMesh;
}
// Update is called once per frame
void Update()
{
}
#if UNITY_EDITOR
private void OnDrawGizmos()
{
Vector3 pos = this.transform.position + Vector3.up * this.transform.localScale.y * .5f;
Gizmos.color = Color.red;
if (this.mesh != null)
Gizmos.DrawWireMesh(this.mesh, pos, this.transform.rotation, this.transform.localScale);
UnityEditor.Handles.color = Color.red;
UnityEditor.Handles.ArrowHandleCap(0, pos, this.transform.rotation, 1f, EventType.Repaint);
UnityEditor.Handles.Label(pos, "SpawnPoint:" + this.ID);
}
#endif
}
(2)写一个编辑器扩展脚本用于生成数据
[MenuItem("Map Tools/Export SpawnPoints")]
public static void ExportSpawnPoints()
{
DataManager.Instance.Load();
Scene current = EditorSceneManager.GetActiveScene();
string currentScene = current.name;
if (current.isDirty)
{
EditorUtility.DisplayDialog("提示", "请先保存当前场景", "确定");
return;
}
if (DataManager.Instance.SpawnPoints == null)
DataManager.Instance.SpawnPoints = new Dictionary<int, Dictionary<int, SpawnPointDefine>>();
foreach (var map in DataManager.Instance.Maps)
{
string sceneFile = "Assets/Levels/" + map.Value.Resource + ".unity";
if (!System.IO.File.Exists(sceneFile))
{
Debug.LogWarningFormat("Scene {0} not existed!", sceneFile);
continue;
}
EditorSceneManager.OpenScene(sceneFile, OpenSceneMode.Single);
SpawnPoint[] spawnPoints = GameObject.FindObjectsOfType<SpawnPoint>();
if (!DataManager.Instance.SpawnPoints.ContainsKey(map.Value.ID))
{
DataManager.Instance.SpawnPoints[map.Value.ID] = new Dictionary<int, SpawnPointDefine>();
}
foreach (var sp in spawnPoints)
{
if (!DataManager.Instance.SpawnPoints[map.Value.ID].ContainsKey(sp.ID))
{
DataManager.Instance.SpawnPoints[map.Value.ID][sp.ID] = new SpawnPointDefine();
}
SpawnPointDefine def = DataManager.Instance.SpawnPoints[map.Value.ID][sp.ID];
def.ID = sp.ID;
def.MapID = map.Value.ID;
def.Position = GameObjectTool.WorldToLogicN(sp.transform.position);
def.Direction = GameObjectTool.WorldToLogicN(sp.transform.forward);
}
}
DataManager.Instance.SaveSpawnPoints();
EditorSceneManager.OpenScene("Assets/Levels/" + currentScene + ".unity");
EditorUtility.DisplayDialog("提示", "刷怪点导出完成", "确定");
}
然后点击运行即可生成。
文件如下:
生成野怪
野怪是生成在地图上的,并且对于不同的玩家,野怪都是一样的,所以野怪应该卸载地图加载的逻辑中,并且是在服务端定时生成的,和客户端解耦。
服务端总体的野怪生成逻辑如下图所示:
野怪生成的时候服务端的Log如下: