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;

相关文章

前言 本文记录unity3D开发环境的搭建 unity安装 unity有中文...
前言 有时候我们希望公告牌跟随镜头旋转永远平行面向屏幕,同...
前言 经过一段时间的学习与实际开发,unity3D也勉强算是强行...
前言 在unity中我们常用的获取鼠标点击的方法有: 1、在3D场...
前言 在之前的例子中,我们都没有用到unity的精髓,例如地形...
这篇文章将为大家详细讲解有关Unity3D中如何通过Animator动画...