微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – Unity 3D Collisiondetection

生成一个Gameobjct speheres数组,并尝试对它们应用一个碰撞器来检测与我的角色控制器的碰撞.

我尝试了serverel方法,没有任何效果.为什么Unity会发现碰撞?

生成数组的脚本:

 public GameObject[] Chunkzufall(float l, float b, int n)
{
    GameObject chunk = new GameObject();
    GameObject[] chunks = new GameObject[n];

    chunkSpeed = new float[n];
    chunkMaxH = new float[n];
    chunkMinH = new float[n];

    for (int j = 0; j < n; j++)
    {
        float h = 1;
        float posX = Random.Range(0.0f, b);
        float posZ = Random.Range(0.0f, l);

        GameObject group = Chunk(h);
        group.transform.Translate(posX, 0.0f, posZ);

        group.transform.parent = chunk.transform;
        chunk.tag = "reset";
        chunk.name = "chunk";

        chunkSpeed[j] = (float) Random.Range(-0.04f, 0.04f);
        chunkMaxH[j] = (float) Random.Range(2.0f, 10.0f);
        chunkMinH[j] = (float) Random.Range(-2.0f, -10.0f);

        chunk.AddComponent<SphereCollider>();
        chunk.GetComponent<SphereCollider>().isTrigger = true;
        chunk.GetComponent<SphereCollider>().radius = 5.0f;

        chunks[j] = chunk;

    }
    return chunks;
}

public void MoveChunks(GameObject[] chunks)
{
    int i = 0;
    foreach(GameObject chunk in chunks)
    {
        Vector3 position = chunk.transform.GetChild(i).position;

        if (position.y >= chunkMaxH[i] || position.y <= chunkMinH[i])
        {
            chunkSpeed[i] = chunkSpeed[i] * -1;
        }

        position.y = position.y - chunkSpeed[i];
        chunk.transform.GetChild(i).position = position;
        chunk.GetComponent<SphereCollider>().center = position;

        i++;
    }
    i = 0;
}

碰撞触发功能

    private void OnTriggerEnter(Collider col) {
    if(col.gameObject.tag == "reset") {
        transform.position = new Vector3(startX, startY, startZ);
        Debug.Log("chunk");
    }
}

解决方法:

要在动态创建的对象上检测触发器,必须启用IsTrigger标志,向对象添加对撞机.该对象还必须附加Rigidbody.看起来你已经有了IsTrigger标志和一个对撞机但是你缺少Rigidbody.

替换这个:

chunk.AddComponent<SphereCollider>();
chunk.GetComponent<SphereCollider>().isTrigger = true;
chunk.GetComponent<SphereCollider>().radius = 5.0f;

chunk.AddComponent<SphereCollider>();
chunk.AddComponent<Rigidbody>(); //ADDS RIGIDBODY COMPONENT
chunk.GetComponent<SphereCollider>().isTrigger = true;
chunk.GetComponent<SphereCollider>().radius = 5.0f;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐