首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >以递增和递减的速度启动物体旋转

以递增和递减的速度启动物体旋转
EN

Stack Overflow用户
提问于 2017-08-22 06:22:05
回答 1查看 39关注 0票数 0

我目前有一个脚本,基本上是让一个对象旋转一旦按下空格键。当再次按下它时,对象将停止。很简单,对吧?

我如何继续做它,例如,通过按空格键激活旋转到速度从0到缓慢到(例如) 1000转/分钟。当我释放空间时,让速度降回0?

这是我到目前为止所知道的:

代码语言:javascript
复制
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class spin : MonoBehaviour
{
    public float speed = 500f;
    public Button starter;
    public Button stopper;
    bool isSpinning = false;

    IEnumerator spinnerCoroutine;

    void Start()
    {
        spinnerCoroutine = spinCOR();
    }

    void Update()
    {
        //Start if Space-key is pressed AND is not Spinning
        if (Input.GetKeyDown(KeyCode.Space) && !isSpinning)
        {
            FidgetSpinnerStart();
        }

        //Stop if Space-key is pressed AND is already Spinning   
        else if (Input.GetKeyDown(KeyCode.Space) && isSpinning)
        {
            FidgetSpinnerStop();
        }
    }

    IEnumerator spinCOR()
    {
        //Spin forever until FidgetSpinnerStop is called 
        while (true)
        {
            transform.Rotate(Vector3.up, speed * Time.deltaTime);
            //Wait for the next frame
            yield return null;
        }
    }

    void FidgetSpinnerStart()
    {
        //Spin only if it is not spinning
        if (!isSpinning)
        {
            isSpinning = true;
            StartCoroutine(spinnerCoroutine);
        }
    }

    void FidgetSpinnerStop()
    {
        //Stop Spinning only if it is already spinning
        if (isSpinning)
        {
            StopCoroutine(spinnerCoroutine);
            isSpinning = false;
        }
    }
}

干杯!

EN

回答 1

Stack Overflow用户

发布于 2017-08-22 06:34:17

更改:

代码语言:javascript
复制
public float speed = 500f;

至:

代码语言:javascript
复制
public float speed = 0f;
public float maxspeed = 500f;
public float acceleration = 1f;

Update中,添加:

代码语言:javascript
复制
if (isSpinning)
{
    if (speed < maxspeed)
    {
        speed += acceleration;
    }
    if (speed > maxspeed)
    {
        speed = maxspeed;
    }
}
else
{
    if (speed > 0)
    {
        speed -= acceleration;
    }
    if (speed < 0)
    {
        speed = 0;
    }
}

增加acceleration的值以使微调器更快地达到最大速度。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45806334

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档