gpt4 book ai didi

c# - 脚本旋转对象超出我的需要

转载 作者:行者123 更新时间:2023-11-30 21:43:58 25 4
gpt4 key购买 nike

我有一个播放器,我使用下面的脚本对其进行轮换。它将玩家旋转 20 度,而不是 10 度(我需要 10 度)。不明白为什么。当我按 q 时,它只执行 1 次。

enter image description here

enter image description here

private UnityStandardAssets.Characters.FirstPerson.FirstPersonController firstPersonController;
public GameObject player;

void Start ()
{
firstPersonController = player.GetComponent<UnityStandardAssets.Characters.FirstPerson.FirstPersonController>();
}

void Update ()
{
StartCoroutine("RotatePlayerDelay");
}

IEnumerator RotatePlayerDelay()
{
Debug.Log("1");
firstPersonController.m_MouseLook.myAngle += 10; // here I have +20, not +10
yield return new WaitForSeconds(0.005f);
firstPersonController.m_MouseLook.myAngle = 0;
Debug.Log("2");
}

附言我需要协程,因为没有它它将永远旋转

最佳答案

与每 Time.fixedDeltaTime 秒调用一次的 FixedUpdate 不同,Update 方法没有确切的时间步长。它是一个协程,依赖于游戏的 FPS 以及所有渲染器和行为的持续时间,因此会动态变化。

您可以将更新视为:

void Start ()
{
StartCoroutine(_update);
}
IEnumerator _update()
{
while(true)
{
Update();
yield return null;
}
}

当您在 Update 方法中启动协程时,您无法判断上一帧是否已结束。如果您的 FPS 低于 1/0.005 = 200.0 FPS,协程的不同调用肯定会相互重叠。

这里的0.005指的是yield return new WaitForSeconds(0.005f)


尽量不要在另一个协程中启动协程:

void Start ()
{
StartCoroutine("RotatePlayerDelay");
}

IEnumerator RotatePlayerDelay()
{
while(true)
{
Debug.Log("1");
firstPersonController.m_MouseLook.myAngle += 10; // here I have +20, not +10
yield return new WaitForSeconds(0.005f);
firstPersonController.m_MouseLook.myAngle = 0;
Debug.Log("2");
yield return new WaitForSeconds(0.005f);
}
}

关于c# - 脚本旋转对象超出我的需要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41159082/

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