简体   繁体   中英

How can i wait until the rotation speed of a object is getting to some value then to slow down?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpinObject : MonoBehaviour
{

    public float rotationMultiplier;
    public GameObject[] objectsToRotate;

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        for (int i = 0; i < objectsToRotate.Length; i++)
        {
            rotationMultiplier += 0.1f;
            objectsToRotate[i].transform.Rotate(Vector3.forward, Time.deltaTime * rotationMultiplier);
        }
    }
}

With this line i speed up the rotation slowly:

rotationMultiplier += 0.1f;

Now i want to add a IF condition so if rotationMultiplier get to for example speed 500 then start slow down like:

rotationMultiplier -= 0.1f;

The problem is that rotationMultiplier is a float so i can't just check IF rotationMultiplier == 500

Add a boolean to check whether you must accelerate or decelerate

private bool slowDown = false;

for (int i = 0; i < objectsToRotate.Length; i++)
{
    if( rotationMultiplier > 500)
        slowDown = true ;
    else if( rotationMultiplier < 0 )
        slowDown = false;

    rotationMultiplier = (slowDown) ? rotationMultiplier - 0.1f : rotationMultiplier + 0.1f;
    objectsToRotate[i].transform.Rotate(Vector3.forward, Time.deltaTime * rotationMultiplier);
}

Otherwise, you could use Mathf.PingPong maybe :

for (int i = 0; i < objectsToRotate.Length; i++)
{
    rotationMultiplier = Mathf.PingPong( Time.time, 500 ) ;
    objectsToRotate[i].transform.Rotate(Vector3.forward, Time.deltaTime * rotationMultiplier);
}

You can use a bool to determine your state (Speed up or slow down)

public bool isIncreasing;


if(rotationMultiplier >= 500)
{
   isIncreasing=false;
}
if(rotationMultiplier <= 0) //or your desired value
{
   isIncreasing=true;
}


if(isIncreasing)
{
 //do your speed up here
}

else
{
 //do your slow down here
}

You can convert float to int then can check

for (int i = 0; i < objectsToRotate.Length; i++)
{
   if(rotationMultiplier >= 500)
   {
      rotationMultiplier -= 0.1f;
   }
   else
   {
     rotationMultiplier += 0.1f;
   }
   objectsToRotate[i].transform.Rotate(Vector3.forward, Time.deltaTime * rotationMultiplier);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM