【发布时间】:2020-02-22 20:17:27
【问题描述】:
按下“C”键时,会创建一个带有刚体的新立方体,并将其添加为“GameObject”的子对象。但是,当按下“F”时,我将爆炸添加到所有子对象,但没有任何反应。我尝试了 AddForce() 并且效果很好,它只是 AddExplosionForce()。我刚刚开始使用 unity,所以这可能是一个愚蠢的错误。
这是我的脚本更新方法:
void Update()
{
if (Input.GetKeyDown(KeyCode.C) || Input.GetMouseButtonDown(0))
{
Vector3 pos = transform.position;
cube = Instantiate(cubePrefab, pos, Quaternion.identity);
GameObject ParentCube = GameObject.Find("GameObject");
cube.transform.parent = ParentCube.transform;
}
if (Input.GetKeyDown(KeyCode.F))
{
foreach (Transform currentCube in transform)
{
Vector3 pointOfExplosion = new Vector3(transform.position.x - 1, transform.position.y - 1, transform.position.z - 1);
currentCube.GetComponent<Rigidbody>().AddExplosionForce(20, pointOfExplosion, 10, 1);
}
}
}
【问题讨论】:
-
而不是
GameObject ParentCube = GameObject.Find("GameObject");(按名称进行全局搜索)您的意思可能是GameObject ParentCube = gameObject,即把它作为当前的父项?顺便说一句,要获取所有刚体子组件,您也可以只说GetComponentsInChildren<Rigidbody>(),这样您就不必逐个遍历所有变换子组件并逐个抓取刚体。此外,您可以在循环之外计算pointOfExplosion,因为它保持不变。此外,尝试创建更大的爆炸力,并确保刚体不是运动学的。 -
当你将立方体添加到父级时,子级的最终世界位置是什么?第一步是通过调试器查看“pointOfExplosion”和“currentCube.transform”的世界坐标。世界位置是否符合您的预期?
-
那不是 C# 代码,而不是 UnityScript(完全不同的编程语言)吗?