【问题标题】:Unity - How to destroy my player by collision?Unity - 如何通过碰撞摧毁我的玩家?
【发布时间】:2020-02-11 19:50:55
【问题描述】:

嗨,我只是试图在我的对象碰到 redcube 时破坏它:) 我在这里使用了代码https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html,但它不起作用。有什么想法吗?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerdeath : MonoBehaviour
{

         void OnCollisionEnter(Collision collision)
         {
             foreach (ContactPoint contact in collision.contacts)
             {
                 Debug.DrawRay(contact.point, contact.normal, Color.white);
                 Debug.Log("collision detected");
             }
             if(collision.relativeVelocity.magnitude > 2)
             {

                 Destroy(gameObject);
             }
         }
}

【问题讨论】:

  • 你试过给redCube贴标签吗?然后在OnCollisionEnter中使用?
  • 它可以工作,但只需要 ontriggerenter

标签: c# unity3d collision-detection destroy gameobject


【解决方案1】:

你可以用这个:-

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerdeath : MonoBehaviour
{

         void OnCollisionEnter(Collision collision)
         {
             foreach (ContactPoint contact in collision.contacts)
             {
                 Debug.DrawRay(contact.point, contact.normal, Color.white);
                 Debug.Log("collision detected");
             }
             if(collision.relativeVelocity.magnitude > 2)
             {

                 Destroy(gameObject);
             }

             if(collision.gameObject.tag=="deathcube")
             {
               Destroy(gameObject); 
             } 
         }
}

注意:在Unity中添加我在截图中给出的标签。

【讨论】:

  • 没有错误,但游戏对象仍然存在。 Debug.Log("检测到冲突");检测碰撞
【解决方案2】:
 void OnTriggerEnter(Collider other)
 {
    if(other.gameObject.tag=="deathcube")
     Destroy(gameObject);  
 }

这很好 :) 但我听说它的性能比 OnCollisionEnter 更重。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    相关资源
    最近更新 更多