using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cubemanger5 : MonoBehaviour
{
public GameObject cubePrefab;
public int numCubes;
public float minSize;
public float maxSize;
public GameObject cubeA;
public float moveSpeed;
private List<GameObject> cubes = new List<GameObject>();
private float totalSurfaceArea = 0f;
// Start is called before the first frame update
void Start()
{
// Instantiate cubes
for (int i = 0; i < numCubes; i++)
{
GameObject cube = Instantiate(cubePrefab);
cube.transform.position = new Vector3(Random.Range(-5f, 5f), Random.Range(0f, 5f), Random.Range(-5f, 5f));
float size = Random.Range(minSize, maxSize);
cube.transform.localScale = new Vector3(size, size, size);
cube.GetComponent<Renderer>().material.color = Random.ColorHSV();
cubes.Add(cube);
// Calculate surface area
totalSurfaceArea += 6 * size * size;
}
}
// Update is called once per frame
void Update()
{ // Move cubeA
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0f, moveVertical);
cubeA.transform.position += movement * moveSpeed * Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Space))
{
// Check for collisions with other cubes
foreach (GameObject cube in cubes)
{
if (cube != cubeA && cube.GetComponent<BoxCollider>().bounds.Intersects(cubeA.GetComponent<BoxCollider>().bounds))
{
Debug.Log("相交");
// Calculate overlapping area
Vector3 overlap = Vector3.Scale(cubeA.GetComponent<BoxCollider>().bounds.size + cube.GetComponent<BoxCollider>().bounds.size - (cubeA.GetComponent<BoxCollider>().bounds.max - cube.GetComponent<BoxCollider>().bounds.min), new Vector3(1f, 0f, 1f));
float overlapArea = overlap.x * overlap.z;
// Subtract overlapping area from total surface area
totalSurfaceArea -= overlapArea;
}
}
// Output total surface area
Debug.Log("Total Surface Area: " + totalSurfaceArea);
}
}
}
标签:cube,物体,float,相交,cubeA,Unity,GetComponent,public,size From: https://www.cnblogs.com/guangzhiruijie/p/17508146.html