以速度增量和减少启动对象旋转

时间:2017-08-21 22:22:05

标签: c# unity3d

我目前有一个脚本,一旦按下Space按钮,它基本上会使对象旋转。再次按下时,对象停止。容易吗?

如何继续制作它,例如,按空格键激活旋转速度从0到慢速(例如)1000次旋转/分钟。当我让空间离开时,让速度降低到0?

这是我到目前为止所拥有的:

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;
        }
    }
}

干杯!

1 个答案:

答案 0 :(得分:0)

变化:

public float speed = 500f;

为:

public float speed = 0f;
public float maxspeed = 500f;
public float acceleration = 1f;

Update中,添加:

if (isSpinning)
{
    if (speed < maxspeed)
    {
        speed += acceleration;
    }
    if (speed > maxspeed)
    {
        speed = maxspeed;
    }
}
else
{
    if (speed > 0)
    {
        speed -= acceleration;
    }
    if (speed < 0)
    {
        speed = 0;
    }
}

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