using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CreatMap : MonoBehaviour
{
public Texture2D texture;
public Color td = Color.yellow;
public Color cd = Color.green;
public GameObject prefab;
float p = 0.05f;
// Start is called before the first frame update
void Start()
{
//生成地图
texture = new Texture2D(220, 200);
VertexHelper vh = new VertexHelper();
for (int x = 0; x < 220; x++)
{
for (int z = 0; z < 200; z++)
{
float y = Mathf.PerlinNoise(x * p, z * p);
Color color = Color.Lerp(td, cd, y);
texture.SetPixel(x, z, color);
float uvx = x * 1f / (texture.width - 1);
float uvy = z * 1f / (texture.height - 1);
vh.AddVert(new Vector3(x, y * 5, z), color, new Vector2(uvx, uvy));
if (x < 200 && z < 200)
{
vh.AddTriangle(x * 200 + z, x * 200 + z + 1, (x + 1) * 200 + z + 1);
vh.AddTriangle(x * 200 + z, (x + 1) * 200 + z + 1, (x + 1) * 200 + z);
}
}
}
//随机生成植物
for (int i = 0; i < 3000; i++)
{
float x = Random.Range(1, 220);
float z = Random.Range(1, 220);
float y = Mathf.PerlinNoise(x * p, z * p) * 5;
GameObject go = Instantiate(prefab, transform);
go.transform.localPosition = new Vector3(x, y, z);
}
texture.Apply();
Mesh mesh = new Mesh();
vh.FillMesh(mesh);
gameObject.AddComponent<MeshFilter>().mesh = mesh;
gameObject.AddComponent<MeshCollider>().sharedMesh = mesh;
Material material = new Material(Shader.Find("Standard"));
material.mainTexture = texture;
gameObject.AddComponent<MeshRenderer>().material = material;
gameObject.AddComponent<NavMeshSourceTag>();
生成Perlin图片
//File.WriteAllBytes(Application.dataPath + "/Map/map.png", texture.EncodeToPNG());
生成mesh网格
//AssetDatabase.CreateAsset(mesh, "Assets/map.asset");
}
}
人物移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class PlayerMove : MonoBehaviour
{
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(1))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))
{
if (hit.transform.CompareTag("Terrain"))
{
GetComponent<NavMeshAgent>().SetDestination(hit.point);
}
}
}
}
}