【问题标题】:How can I get smooth random movement (2D Unity)?如何获得平滑的随机运动(2D Unity)?
【发布时间】:2021-03-10 16:52:17
【问题描述】:

我正在使用 Random.onUnitSphere 来模拟漂浮在周围的气泡争夺位置。尽管动作过于“生涩”,但效果很好。我想创建相同的效果,但放慢速度并做出更平滑的随机运动。无论如何我可以轻松实现这一目标吗?这是我的代码:

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

【问题讨论】:

    标签: unity3d 2d rigid-bodies


    【解决方案1】:

    Perlin 噪声随机游走器应该可以工作

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

    在更新函数中

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

    我还应该提到,这种方法不应该与 RigidBody.ApplyForce() 一起使用,但我通常不使用 Unity 的默认物理,所以它可以。无论如何,它不应该改变任何东西。

    【讨论】:

    • 嘿,谢谢您的回答。我似乎真的无法让 Perlin 方法在这里工作以实现我想要实现的目标。不过我很欣赏这个想法,这是我没有想到的,并让我走上了一条更多发现 Perlin 方法可以做什么的道路(主要是程序生成的地形等)
    • 感谢您的反馈,但我想问一下您想得到什么效果?
    • 我正在尝试使 2D 精灵气泡在 y 和 x 轴上随机平滑地浮动到位。 rb.AddRelativeForce(Random.onUnitSphere * speed);做到了这一点,但动作很疯狂。
    • 也许是二维步行者?如果你想要粒子,我会使用统一的粒子系统进行侦察。我认为只需在 walker 函数中将 y 设置为 0 即可从 3d 中获取 2d walker。 Vector3 vector = new Vector3(x, 0, z);
    • 您需要真正推动其他物体的气泡吗?因为否则粒子系统将是一个好用的东西——我自己用它来制作气泡。它具有内置的“噪音”功能,可以创建整洁、随机的动作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多