94 lines
3.0 KiB
C#
94 lines
3.0 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class SorghumFieldController : MonoBehaviour
|
|
{
|
|
public MeshRenderer fieldArea;
|
|
//public GameObject SorghumPrefab;
|
|
public bool randomRotate = false;
|
|
public float rowDistance = 1;
|
|
public float strainDistance = 1;
|
|
public float diseasedRate = 0;
|
|
|
|
public void InitSorghum(float RowDistance, float StrainDistance, float DiseasedRate, bool RandomRotate = false)
|
|
{
|
|
|
|
GameObject SorghumPrefab = Resources.Load<GameObject>("Prefabs/高粱预制体");
|
|
if (SorghumPrefab == null || fieldArea == null)
|
|
{
|
|
Debug.LogError("预制体或农田区域未分配!");
|
|
return;
|
|
}
|
|
|
|
// 获取农田的包围盒信息
|
|
BoxCollider fieldCollider = fieldArea.GetComponent<BoxCollider>();
|
|
if (fieldCollider == null)
|
|
{
|
|
Debug.LogError("农田区域缺少BoxCollider组件");
|
|
return;
|
|
}
|
|
Bounds bounds = fieldCollider.bounds;
|
|
|
|
// 计算农田边界
|
|
float minX = bounds.min.x;
|
|
float maxX = bounds.max.x;
|
|
float minZ = bounds.min.z;
|
|
float maxZ = bounds.max.z;
|
|
|
|
// 获取农田表面高度(假设为平面)
|
|
float groundY = fieldArea.transform.position.y;
|
|
|
|
// 按行生成农作物
|
|
for (float x = minX; x <= maxX; x += RowDistance)
|
|
{
|
|
// 按植株间距生成单行作物
|
|
for (float z = minZ; z <= maxZ; z += StrainDistance)
|
|
{
|
|
// 生成位置(自动对齐地面高度)
|
|
Vector3 spawnPos = new Vector3(x, groundY, z);
|
|
|
|
// 实例化并挂载到农田下
|
|
GameObject obj = Instantiate(
|
|
SorghumPrefab,
|
|
spawnPos,
|
|
Quaternion.identity,
|
|
fieldArea.transform
|
|
);
|
|
}
|
|
}
|
|
|
|
SorghumController[] sorghumControllers = FindObjectsOfType<SorghumController>();
|
|
int DisCount = (int)(sorghumControllers.Length * DiseasedRate);
|
|
for (int i = 0; i < DisCount; i++)
|
|
{
|
|
int iter = (int)(sorghumControllers.Length * UnityEngine.Random.value);
|
|
if (iter >= sorghumControllers.Length) iter = sorghumControllers.Length - 1;
|
|
if (iter < 0) iter = 0;
|
|
sorghumControllers[iter].Init(SorghumState.Diseased, RandomRotate);
|
|
sorghumControllers[iter] = sorghumControllers[sorghumControllers.Length - 1];
|
|
SorghumController[] newArry = new SorghumController[sorghumControllers.Length - 1];
|
|
Array.Copy(sorghumControllers, newArry, sorghumControllers.Length - 1);
|
|
}
|
|
|
|
foreach (var item in sorghumControllers)
|
|
{
|
|
item.Init(SorghumState.Healthy, RandomRotate);
|
|
}
|
|
}
|
|
|
|
|
|
//// Start is called before the first frame update
|
|
void Start()
|
|
{
|
|
InitSorghum(rowDistance, strainDistance, diseasedRate, randomRotate);
|
|
}
|
|
|
|
//// Update is called once per frame
|
|
//void Update()
|
|
//{
|
|
|
|
//}
|
|
}
|