Unity如何判断两物体相交
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);
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!