简体   繁体   English

Unity:使用标签的 2D 碰撞检测

[英]Unity: 2D Collision Detection Using Tags

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Bullet")
    {
        Destroy(gameObject);
        Debug.Log("hit");
    }
}

This is my code, I appreciate that there is a lot of other sources out there however I have looked on the internet and just cannot understand where im going wrong.这是我的代码,我很欣赏那里有很多其他来源,但是我在互联网上查看过,只是无法理解我哪里出错了。 I know its probably something so small.我知道它可能是这么小的东西。 I'm attempting to get on collision detect destroy "this" game object using the tag.我正在尝试使用标签进行碰撞检测销毁“这个”游戏对象。 The Bullet prefab has the Bullet tag and is spelt exactly the same, both gameObjects have both a rigidbody and a 2D box collider. Bullet 预制件具有 Bullet 标签并且拼写完全相同,两个游戏对象都有一个刚体和一个 2D 盒子碰撞器。

Any help will be great.任何帮助都会很棒。

things to check:检查事项:

  • Rigibody2D are simulated (in inspector Rigidbody2D simulated check is true) Rigibody2D 被模拟(在检查员 Rigidbody2D 中模拟检查为真)
  • none of the colliders are set to isTrigger没有一个碰撞器被设置为 isTrigger
  • because this is 2d so make sure both sprites are on the same layer order or z-order因为这是 2d 所以确保两个精灵都在相同的层顺序或 z 顺序上
  • try debugging and check which object is bullet hitting尝试调试并检查哪个对象被子弹击中

(and i assume you have Rigidbody2D not Rogidbody like you mentioned in your question) (我假设你有 Rigidbody2D 而不是你在问题中提到的 Rogidbody)

(if all of these are checked then just for testing try to decrease the speed of bullet, if bullet is going too fast then try changing “Collision Detection” to continues) (如果所有这些都被选中,那么只是为了测试尝试降低子弹的速度,如果子弹速度太快,那么尝试将“碰撞检测”更改为继续)

most imported thing “debug” and debug before destroying not after大多数进口的东西“调试”和调试之前销毁而不是之后

Better practive is to use CompareTag instead:更好的做法是使用CompareTag代替:

private void OnCollisionEnter(Collision other) {
    if(other.gameObject.CompareTag("Ground")) {
        isJumping = false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM