Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

c# - How to put random speed on the position of the y-axis only?

Sorry, I'm a beginner in Unity but I want to move a gameobject on the Y-axis only and have it move with random speed so that sometimes it moves fast and sometimes slower.

this is my code. (it jitters because i figured out my mistake is I put the random speed on the update but I don't know how to fix it)

public class RandomUpDown : MonoBehaviour
{
     [SerializeField] float minSpeed = 1f;

     [SerializeField] float maxSpeed = 2f;
     
     [SerializeField] float height = 4f;

     Vector3 pos;

     private void Start()
     {
         pos = transform.position;
     }

     void Update()
     {
        float randomSpeed = Random.Range(minSpeed, maxSpeed);
        float newY = Mathf.Sin(Time.time * randomSpeed) * height + pos.y;  
        transform.position = new Vector3(transform.position.x, newY, transform.position.z);
     } 
} 
question from:https://stackoverflow.com/questions/65886259/how-to-put-random-speed-on-the-position-of-the-y-axis-only

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

it really depends on what you want, but you can do this with a coroutine and a loop.

for example:

void Start()
{
    StartCoroutine(myRandLoop)
}

public IEnumerator myRandLoop()
{
    while(true)
    {
        float randomSpeed = Random.Range(minSpeed, maxSpeed);
        float newY = Mathf.Sin(Time.time * randomSpeed) * height + pos.y;  
        transform.position = new Vector3(transform.position.x, newY, transform.position.z);
        yield return new WaitForSeconds(delayAmount)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...