加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 旋转脚本问题?

发布时间:2020-12-15 22:28:38 所属栏目:百科 来源:网络整理
导读:用户释放鼠标按钮时调用此脚本: float rot_duration = 3f;float rot_speed = 1.8f;Quaternion final_rot;void Start(){ cubeMesh = GameObject.FindWithTag("CubeMesh"); Vector3 initial_rot = transform.rotation.eulerAngles; final_rot = Quaternion.Eu
用户释放鼠标按钮时调用此脚本:

float rot_duration = 3f;
float rot_speed = 1.8f;
Quaternion final_rot;

void Start()
{
    cubeMesh = GameObject.FindWithTag("CubeMesh");

    Vector3 initial_rot = transform.rotation.eulerAngles;
    final_rot = Quaternion.Euler(new Vector3(initial_rot.x,initial_rot.y,180));
}

public void Update()
{
    if (Input.GetMouseButtonUp(0)) 
    {
        StartCoroutine (DelayRotate (0.1F));
    }
}

IEnumerator DelayRotate(float waitTime)
{
        yield return new WaitForSeconds (waitTime);
        float rot_elapsedTime = 0.0F;
        while (rot_elapsedTime < rot_duration) {
        cubeMesh.transform.rotation = Quaternion.Slerp (transform.rotation,final_rot,rot_elapsedTime);
            rot_elapsedTime += Time.deltaTime * rot_speed;
            yield return null;
        }
}

鼠标按钮释放后,此脚本使游戏对象旋转0.1秒.问题是它快速“翻转”GameObject然后开始旋转.

由于final_rot2 = Quaternion.Euler(new Vector3(initial_rot.x,180)),我认为它正在翻转; (因为180值)我该怎么做?

解决方法

我仔细查看了代码,我发现了两个错误.

1.导致问题的一个错误是:

cubeMesh.transform.rotation = Quaternion.Slerp (transform.rotation,rot_elapsedTime);

我上面的那个人说你应该用cubeMesh.transform.rotation替换transform.rotation.这很接近但不会工作.你想要的是在while循环之外获取GameObject的当前位置并将其存储在某个地方,然后你可以在稍后的while循环中使用它.例如,

Quaternion currentLocation = cubeMesh.transform.rotation;
while(...){
  cubeMesh.transform.rotation = Quaternion.Slerp (currentLocation,rot_elapsedTime);
...Other codes
}

2.我发现的另一个错误是,你似乎试图在一段时间内旋转对象,因为你有一个名为rot_duration的变量.

如果这是真的,那么当你执行Quaternion.Slerp(transform.rotation,rot_elapsedTime);时就失败了.

如果希望对象在rot_duration时间内旋转,请将rot_elapsedTime更改为rot_elapsedTime / rot_duration.同时删除rot_speed,因为如果你想随着时间的推移旋转它将无法工作.

如果这不是你想要做的,那么我发现的第一个错误应该可以解决你的问题.

您的最终代码应如下所示:

float rot_duration = 10f;
float rot_speed = 3f;
Quaternion final_rot;
GameObject cubeMesh;

void Start()
{
    cubeMesh = GameObject.FindWithTag("CubeMesh");

    Vector3 initial_rot = transform.rotation.eulerAngles;
    final_rot = Quaternion.Euler(new Vector3(initial_rot.x,180));
}

public void Update()
{
    if (Input.GetMouseButtonUp(0))
    {
        StartCoroutine(Delay(1));
    }
}

IEnumerator Delay(float waitTime)
{
    yield return new WaitForSeconds(waitTime);
    float rot_elapsedTime = 0.0F;

    //Get the current rotation 
    Quaternion currentLocation = cubeMesh.transform.rotation;

    while (rot_elapsedTime < rot_duration)
    {
        rot_elapsedTime += Time.deltaTime;
        cubeMesh.transform.rotation = Quaternion.Slerp(currentLocation,rot_elapsedTime / rot_duration);
        yield return null;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读