成品
先放成品,原理与解释等以后补上
输入:地形大致样子
过程中:生成高度图
结果:生成体素地形
结果:优化后的碰撞箱
主要代码:
using FullInspector;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[ExecuteInEditMode]
public class WorldBuilder : BaseBehavior<FullSerializerSerializer> {
public GameObject sandBox;
public DepthCamera depthCamera;
public int groundHeight;
public Texture2D texture;
public Transform pointA;//drop
public Transform pointB;//drop
public Transform terrainParent;
public Transform terrainColliderParent;
public LayerMask mask;
public int layer = 16;
public List<GameObject> nowSelectTerrain;
public List<GameObject> nowSelectSubTerrain;
//public List<GameObject> nowSelectObj;
//public bool enableDrawLine = false;
//public KeyCode drawKey = KeyCode.B;
//public float radius = 5;
//public float density = 0.1f;
//public AnimationCurve strength;
int dertaFrame = 5;
int frameCounter = 0;
Vector3 textureSize;
Vector3 terrainSize;
Vector3 posMin, posMax;
Camera sceneCamera;
Vector3 sandBoxSize;
Vector3 sandBoxOffset;
//public Vector3 bufferedPosition = Vector3.zero;
// Update is called once per frame
void Update() {
//if(enableDrawLine ) {
// if (CanUpdateLine()) {
// sceneCamera = SceneView.lastActiveSceneView.camera;
// var ray = sceneCamera.ScreenPointToRay(Input.mousePosition);
// RaycastHit hit;
// Physics.Raycast(ray,out hit,100, mask.value);
// bufferedPosition = hit.point;
// Debug.DrawRay(hit.point, Vector3.up * (posMax.y - posMin.y));
// }
//}
}
bool CanUpdateLine() {
frameCounter++;
if (frameCounter >= dertaFrame) {
frameCounter = 0;
return true;
} else return false;
}
[InspectorButton]
public void Build() {
Clean();
UpdateParams();
depthCamera.Snap(callback:CreateTerrain);
}
[InspectorButton]
public void BuildWithCorrentSnap() {
Clean();
UpdateParams();
CreateTerrain();
}
[InspectorButton]
void Clean(string tag = "Terrain") {
for(int i = terrainParent.childCount - 1; i >= 0; i--) {
var obj = terrainParent.GetChild(i) ;
if (obj.tag == tag) {
obj.SetParent(transform);
DestroyImmediate(obj.gameObject);
}
}
for (int i = terrainColliderParent