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

Physics.IgnoreLayerCollision

建议更改

成功!

感谢您帮助我们提高 Unity 文档的质量。虽然我们无法接受所有提交,但我们确实会阅读用户提出的每项更改建议,并在适用的情况下进行更新。

关闭

提交失败

由于某种原因,您的更改建议无法提交。请<a>稍后再试</a>。感谢您抽出时间帮助我们提高 Unity 文档的质量。

关闭

取消

声明

public static void IgnoreLayerCollision(int layer1, int layer2, bool ignore = true);

描述

使碰撞检测系统忽略 layer1 中任何碰撞体与 layer2 中任何碰撞体之间的所有碰撞。

请注意,IgnoreLayerCollision 会重置受影响碰撞体的触发状态,因此您可能会收到 OnTriggerExit 和 OnTriggerEnter 消息以响应此调用。

您可以在物理检查器中为项目中的任何图层组合设置默认值。

其他资源:Physics.GetIgnoreLayerCollisionPhysics.IgnoreCollision

//Attach this script to a GameObject and make sure it has a Rigidbody component
//Make a second GameObject with a Collider to test collisions on. Make sure both GameObjects are the same on the y and z axes

//This script stops collisions between two layers (in this case layers 0 and 8). Set up a new layer in the Inspector window by clicking the Layer option. //Next click “Add Layer”. Then, assign this layer to the second GameObject.

//In Play Mode, press the left and right keys to move the Rigidbody to the left and right. If your first GameObject is in layer 0 and your second GameObject is in layer 8, the collision is ignored.

using UnityEngine;

public class Example : MonoBehaviour { //Set the speed number in the Inspector window public float m_Speed; Rigidbody m_Rigidbody;

void Start() { //Fetch the Rigidbody component from the GameObject m_Rigidbody = GetComponent<Rigidbody>(); //Ignore the collisions between layer 0 (default) and layer 8 (custom layer you set in Inspector window) Physics.IgnoreLayerCollision(0, 8); }

void Update() { //Press right to move the GameObject to the right. Make sure you set the speed high in the Inspector window. if (Input.GetKey(KeyCode.RightArrow)) { m_Rigidbody.AddForce(Vector3.right * m_Speed); }

//Press the left arrow key to move the GameObject to the left if (Input.GetKey(KeyCode.LeftArrow)) { m_Rigidbody.AddForce(Vector3.left * m_Speed); } }

//Detect when there is a collision void OnCollisionStay(Collision collide) { //Output the name of the GameObject you collide with Debug.Log("I hit the GameObject : " + collide.gameObject.name); } }