问题描述
我正在使用 Random.onUnitSphere 来模拟漂浮在周围争抢位置的气泡。尽管运动太“生涩”,但效果很好。我想创建相同的效果,但放慢速度并进行更平滑的随机运动。无论如何我可以轻松实现这一目标吗?这是我的代码:
private void Update()
{
if (floaty == true)
{
rb.AddRelativeForce(Random.onUnitSphere * speed);
speed = 0.06f;
}
}
解决方法
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 的默认物理,所以它可以。无论如何,它不应该改变任何东西。