using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
[Serializable]
public class BoundCalcSet
{
public string name;
public Bounds bounds;
public Vector3 minOfWorld;
public Vector3 maxOfWorld;
public Vector3 sizeofWorld;
}
public class BoundBoxTest : MonoBehaviour
{
public Transform min;
public Transform max;
public Vector3 minPos;
public Vector3 maxPos;
public Bounds thisBounds;
public List<BoundCalcSet> boundCalSets = new List<BoundCalcSet>();
[Space(20)]
[Header("ForDebug")]
public Vector3 minPosEx;
public Vector3 maxPosEx;
private void OnEnable()
{
minPosEx = min.position;
maxPosEx = max.position;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
var tempEuler = this.transform.eulerAngles;
this.transform.eulerAngles = Vector3.zero;
minPos = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
maxPos = new Vector3(float.MinValue, float.MinValue, float.MinValue);
var col = this.GetComponent<BoxCollider>();
if (col)
{
Destroy(col);
}
col = this.AddComponent<BoxCollider>();
boundCalSets.Clear();
foreach (var mf in this.GetComponentsInChildren<MeshFilter>())
{
var boundCalSet = new BoundCalcSet();
boundCalSet.name = mf.name;
boundCalSet.bounds = mf.mesh.bounds;
Vector3 scale = mf.transform.lossyScale;
Vector3 min = mf.mesh.bounds.min;
Vector3 max = mf.mesh.bounds.max;
Vector3 size = mf.mesh.bounds.size;
boundCalSet.minOfWorld = new Vector3(scale.x * min.x, scale.y * min.y, scale.z * min.z) + mf.transform.position;
boundCalSet.maxOfWorld = new Vector3(scale.x * max.x, scale.y * max.y, scale.z * max.z) + mf.transform.position;
boundCalSet.sizeofWorld = new Vector3(scale.x * size.x, scale.y * size.y, scale.z * size.z);
boundCalSets.Add(boundCalSet);
}
foreach (var set in boundCalSets)
{
minPos = new Vector3(Mathf.Min(minPos.x, set.minOfWorld.x, set.maxOfWorld.x)
, Mathf.Min(minPos.y, set.minOfWorld.y, set.maxOfWorld.y)
, Mathf.Min(minPos.z, set.minOfWorld.z, set.maxOfWorld.z));
maxPos = new Vector3(Mathf.Max(maxPos.x, set.minOfWorld.x, set.maxOfWorld.x)
, Mathf.Max(maxPos.y, set.minOfWorld.y, set.maxOfWorld.y)
, Mathf.Max(maxPos.z, set.minOfWorld.z, set.maxOfWorld.z));
}
thisBounds = new Bounds();
thisBounds.min = minPos;
thisBounds.max = maxPos;
col.size = thisBounds.size;
col.center = thisBounds.center - this.transform.position;
this.transform.eulerAngles = tempEuler;
}
}
}