如何检测与预制件孩子的碰撞 [英] How do I detect collision with a child of a prefab

查看:97
本文介绍了如何检测与预制件孩子的碰撞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始学习Unity并决定做一些练习.因此,我认为开发"Flappy Bird"作为实验将是很棒的.但是我已经遇到了问题.您知道,当您在管道之间飞行时,您会获得积分.为此,我制作了一个带有两个管道的预制件,两个管道之间有一个空的游戏对象(触发器),以检测与之碰撞的情况.但是,当我调用OnCollisionEnter2D方法时,它检测到与预制件的碰撞,而不是与其中的触发器或管道的碰撞.你可以帮帮我吗?如何检测与预制件孩子的碰撞?

I've started studying Unity and decided to do some practice. So, I thought that it would be awesome to develope "Flappy Bird" as an experiment. But I've faced with the problem. You know, when you fly between pipes, you earn a point. To do that I made a prefab with two pipes and an empty game object (trigger) between them to detect collision with it. But when I call OnCollisionEnter2D method, it detects collision with a prefab, not with the trigger or pipes in it. Could you help me? How do I detect collision with a child of a prefab?

推荐答案

就像Uri Popov回答的一样,使用OnTriggerEnter2D()您需要执行以下几点操作:
1.将OnTriggerEnter2D()脚本放在空游戏对象上,不要忘记将collider2D附加到空对象上.
2.确保已在collider2D选项中选中isTrigger
3.还请确保您的玩家具有标签,您可以自己制作标签,在本示例中,我将"Player"标签赋予我的玩家游戏对象
4.示例脚本(我已经厌倦并工作了)

like what Uri Popov answered, use OnTriggerEnter2D() there are several points you need to do :
1. Put the OnTriggerEnter2D() Script on your empty game object, and don't forget to attached collider2D on your empty object.
2. make sure isTrigger checked in collider2D option
3. also make sure your player has tag, you can make the tag your own, in this example i give "Player" tag to my player game object
4. the example script(i tired it and worked)

public class YourTriggerScript: MonoBehaviour {
void Start () {

}

// Update is called once per frame
void Update () {


}

void OnTriggerEnter2D(Collider2D collider)
{
    if (collider.GetComponent<Collider2D>().tag == "Player") 
    {
        Debug.Log ("Collided");
        // do something or you can + your point here
    }
}
}  

希望对您有帮助

这篇关于如何检测与预制件孩子的碰撞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆