How can I get smooth random movement (2D Unity)?

Viewed 1016

I'm using Random.onUnitSphere to simulate bubbles floating around jostling for position. It works well although the movement is too "jerky". I'd like to create the same effect but slow it down and make smoother random movements. Is there anyway I can easily achieve this? Here's my code:

private void Update()
{
     if (floaty == true)
     {
         rb.AddRelativeForce(Random.onUnitSphere * speed);
         speed = 0.06f;
     }
}
1 Answers

A Perlin noise random walker should work


//There are probably better ways to do this.
Vector3 RandomSmoothPointOnUnitSphere(float time)
{
  
  //Get the x of the vector
  float x = Math.PerlinNoise(time, /* your x seed */);
  
  //Get the y of the vector
  float y = Math.PerlinNoise(time, /* your y seed */);
  
  //Get the z of the vector
  float z = Math.PerlinNoise(time, /* your z seed */);
  
  //Create a vector3
  Vector3 vector = new Vector3(x, y, z);
  
  //Normalize the vector and return it
  return Vector3.Normalize(vector);
  
}

And in the Update function

if (floaty)
{
  
  //Get the vector
  Vector3 movementvector = RandomSmoothPointOnUnitSphere(Time.time);
  
  //You can also use CharacterController.Move()
  transform.Translate(movementvector * Time.deltatime);
  
}

I should also mention that this approach shouldn't work with RigidBody.ApplyForce(), but I don't usually use Unity's default physics, so it may. Regardless, it shouldn't change anything.

Related