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