gpt4 book ai didi

c# - 检测所有骰子何时停止移动

转载 作者:太空宇宙 更新时间:2023-11-03 20:54:49 24 4
gpt4 key购买 nike

这似乎是一个如此简单的问题,但我很难解决。我正在掷一些骰子 (GameObject) 并尝试检测它们何时都停止移动(这样我就可以计算分数)。

这是我尝试过的:

public class GameManager : MonoBehaviour
{
public GameObject[] _dice;

public Vector3 _rollStartPosition;
public float _rollForce;
public float _rollTorque;

bool anyDieIsMoving = false;

void FixedUpdate()
{
if (!anyDieIsMoving && Input.GetMouseButtonDown(0))
RollDice();
}

void RollDice()
{
foreach (var die in _dice)
{
// Roll() adds force and torque from a given starting position
die.GetComponent<Die>()
.Roll(_rollStartPosition, Random.onUnitSphere * _rollForce, Random.onUnitSphere * _rollTorque);
}

StartCoroutine(CheckIfDiceAreMoving());

// Calculate score and do something with it...
}

IEnumerator CheckIfDiceAreMoving()
{
foreach (var die in _dice)
{
var dieRigidbody = die.GetComponent<Rigidbody>();
if (!dieRigidbody.IsSleeping())
{
anyDieIsMoving = true;
yield return null;
}
}
}
}

上面代码的问题在于它会在所有骰子停止移动之前立即尝试计算分数(我通过添加一堆 Debug.Log() 语句发现了这一点)。

如何才能等到所有的骰子都停止移动后再计算分数?

最佳答案

您必须使 RollDice 成为协程函数,然后您可以让出或等待 CheckIfDiceAreMoving 函数以 yield return 返回。更好的是,将 if (!dieRigidbody.IsSleeping()) 转换为 while (!dieRigidbody.IsSleeping()) 以便 CheckIfDiceAreMoving 函数直到所有骰子停止移动才会退出。此外,检查 Update 函数中的输入,而不是用于移动 RigidbodyFixedUpdate

这是重构代码:

public class GameManager : MonoBehaviour
{
public GameObject[] _dice;

public Vector3 _rollStartPosition;
public float _rollForce;
public float _rollTorque;
bool doneRolling = true;

void Update()
{
if (doneRolling && Input.GetMouseButtonDown(0))
{
StartCoroutine(RollDice());
}
}

IEnumerator RollDice()
{
doneRolling = false;

foreach (var die in _dice)
{
// Roll() adds force and torque from a given starting position
die.GetComponent<Die>()
.Roll(_rollStartPosition, Random.onUnitSphere * _rollForce, Random.onUnitSphere * _rollTorque);
}

//Wait until all dice tops moving
yield return CheckIfDiceAreMoving();


// Calculate score and do something with it...


//Set doneRolling to true so that we call this funtion again
doneRolling = true;
}

IEnumerator CheckIfDiceAreMoving()
{
foreach (var die in _dice)
{
var dieRigidbody = die.GetComponent<Rigidbody>();
//Wait until all dice stops moving
while (!dieRigidbody.IsSleeping())
{
yield return null;
}
}
}
}

关于c# - 检测所有骰子何时停止移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51644503/

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