创建Editor文件夹新建脚本用以创建地板
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
public class CreateMap : MonoBehaviour
{
// Start is called before the first frame update
[MenuItem("Tools/CreateMap")]
static void Createmap()
{
GameObject go = new GameObject("Map");
Mesh mesh = new Mesh();
VertexHelper vh = new VertexHelper();
for (int x = 0; x < 20; x++)
{
for (int z = 0; z < 20; z++)
{
float y = Mathf.PerlinNoise(x * 0.1f, z * 0.1f);
Vector2 pos = new Vector2((float)x / (20 - 1), (float)z / (20 - 1));
vh.AddVert(new Vector3(x, y * 3, z), Color.white, pos);
if (x < 20 - 1 && z < 20 - 1)
{
vh.AddTriangle(x * 20 + z, x * 20 + z + 1, (x + 1) * 20 + z + 1);
vh.AddTriangle(x * 20 + z, (x + 1) * 20 + z + 1, (x + 1) * 20 + z);
}
}
}
vh.FillMesh(mesh);
go.AddComponent<MeshFilter>().mesh = mesh;
go.AddComponent<MeshCollider>().sharedMesh = mesh;
go.AddComponent<MeshRenderer>().material=new Material(Shader.Find("Standard"));
}
// Update is called once per frame
void Update()
{
}
}
效果
使用此方法绘制出的地板会跟实际代码运行中绘制出的地板有所出入但总体来说问题不大
摇杆
结构
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class ETC : MonoBehaviour,IDragHandler,IEndDragHandler
{
RectTransform rect;
public int r;
Vector3 startpos;
// Start is called before the first frame update
void Start()
{
startpos = transform.position;
rect = GetComponent<RectTransform>();
}
// Update is called once per frame
void Update()
{
}
public void OnDrag(PointerEventData eventData)
{
if (Vector3.Distance(Input.mousePosition,startpos)<=r)
{
transform.position = Input.mousePosition;
}
else
{
Vector3 dir = Input.mousePosition - startpos;
dir.Normalize();
transform.position = dir * r + startpos;
}
}
public void OnEndDrag(PointerEventData eventData)
{
transform.position = startpos;
}
public float GetAxis(string name)
{
if (name=="Horizontal")
{
return rect.anchoredPosition.x / r;
}
if (name == "Vertical")
{
return rect.anchoredPosition.y / r;
}
return 0;
}
}