gpt4 book ai didi

c# - Unity 3D 碰撞检测

转载 作者:太空狗 更新时间:2023-10-30 00:59:52 27 4
gpt4 key购买 nike

我生成了一个 Gameobjct 球体数组,并尝试对它们应用碰撞器以检测与我的角色 Controller 的碰撞。

我尝试了 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;

关于c# - Unity 3D 碰撞检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52434542/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com