版本:Unity 6 (6000.0)
语言英语
  • C#

物理.OverlapBox

建议更改

成功!

感谢您帮助我们提高 Unity 文档的质量。虽然我们无法接受所有提交,但我们会阅读每个用户建议的更改并进行必要的更新。

关闭

提交失败

由于某些原因,您建议的更改无法提交。请在<a>几分钟后重试</a>。感谢您花时间帮助我们提高 Unity 文档的质量。

关闭

取消

声明

public static Collider[] OverlapBox(Vector3 center, Vector3 halfExtents, Quaternion orientation = Quaternion.identity, int layerMask = AllLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);

参数

center 盒子中心。
halfExtents 以每个维度计算,盒子的一半。
orientation 盒子的旋转角度。
layerMask 在进行射线投射时用来有选择地忽略碰撞器的图层掩码
queryTriggerInteraction 指定此查询是否应命中触发器。

返回

Collider[] 与当前盒子重叠的碰撞器。

描述

查找所有与给定盒子接触或在盒子内部的碰撞器。

创建一个用户定义且不可见的盒子,然后通过输出与盒子接触的任何碰撞器来测试碰撞。

//Attach this script to your GameObject. This GameObject doesn’t need to have a Collider component
//Set the Layer Mask field in the Inspector to the layer you would like to see collisions in (set to Everything if you are unsure).
//Create a second Gameobject for testing collisions. Make sure your GameObject has a Collider component (if it doesn’t, click on the Add Component button in the GameObject’s Inspector, and go to Physics>Box Collider).
//Place it so it is overlapping your other GameObject.
//Press Play to see the console output the name of your second GameObject

//This script uses the OverlapBox that creates an invisible Box Collider that detects multiple collisions with other colliders. The OverlapBox in this case is the same size and position as the GameObject you attach it to (acting as a replacement for the BoxCollider component).

using UnityEngine;

public class OverlapBoxExample : MonoBehaviour { bool m_Started; public LayerMask m_LayerMask;

void Start() { //Use this to ensure that the Gizmos are being drawn when in Play Mode. m_Started = true; }

void FixedUpdate() { MyCollisions(); }

void MyCollisions() { //Use the OverlapBox to detect if there are any other colliders within this box area. //Use the GameObject's centre, half the size (as a radius) and rotation. This creates an invisible box around your GameObject. Collider[] hitColliders = Physics.OverlapBox(gameObject.transform.position, transform.localScale / 2, Quaternion.identity, m_LayerMask); int i = 0; //Check when there is a new collider coming into contact with the box while (i < hitColliders.Length) { //Output all of the collider names Debug.Log("Hit : " + hitColliders[i].name + i); //Increase the number of Colliders in the array i++; } }

//Draw the Box Overlap as a gizmo to show where it currently is testing. Click the Gizmos button to see this void OnDrawGizmos() { Gizmos.color = Color.red; //Check that it is being run in Play Mode, so it doesn't try to draw this in Editor mode if (m_Started) //Draw a cube where the OverlapBox is (positioned where your GameObject is as well as a size) Gizmos.DrawWireCube(transform.position, transform.localScale); } }