BufferGeometry
Object3D
Raycaster
Camera
CubeCamera
PerspectiveCamera
OrthographicCamera
StereoCamera
Clock
Curve
CurvePath
Path
Shape
ShapePath
ArrowHelper
AxesHelper
BoxHelper
Box3Helper
CameraHelper
DirectionalLightHelper
GridHelper
PolarGridHelper
HemisphereLightHelper
PlaneHelper
PointLightHelper
SkeletonHelper
SpotLightHelper
Light
PointLight
RectAreaLight
SpotLight
DirectionalLight
HemisphereLight
LightShadow
PointLightShadow
AnimationLoader
AudioLoader
BufferGeometryLoader
CompressedTextureLoader
CubeTextureLoader
DataTextureLoader
FileLoader
ImageBitmapLoader
ImageLoader
Loader
LoaderUtils
MaterialLoader
ObjectLoader
TextureLoader
LoadingManager
Material
Box2
Box3
Color
Cylindrical
Euler
Frustum
Interpolant
Line3
MathUtils
Matrix3
Matrix4
Plane
Quaternion
AnimationAction
AnimationClip
AnimationMixer
AnimationObjectGroup
AnimationUtils
keyframeTrack
PropertyBinding
PropertyMixer
BooleanKeyframeTrack
QuaternionKeyframeTrack
StringKeyframeTrack
Audio
AudioAnalyser
AudioContext
AudioListener
PositionalAudio

MathUtils.randFloat()

randFloat方法返回一个指定范围内的随机浮点数。

MathUtils.randFloat(min, max);

参数

  • min(必需):类型为浮点数,表示随机数的最小值。
  • max(必需):类型为浮点数,表示随机数的最大值。

返回值

  • 返回一个指定范围内的随机浮点数。

示例

const randomFloat = MathUtils.randFloat(0, 10);
console.log(randomFloat); //输出0到10之间的随机浮点数

用例

randFloat方法是可用于生成随机动画效果中的转换,还可以在游戏中创建随机生成的障碍、元素等。例如,可以使用此函数创建具有随机速度和颜色属性的粒子。

for(let i=0; i<100; i++){
  const geometry = new THREE.SphereGeometry(1, 20, 20);
  const material = new THREE.MeshBasicMaterial({color: Math.random() * 0xffffff});
  const mesh = new THREE.Mesh(geometry, material);
  
  mesh.position.set(
    MathUtils.randFloat(-10, 10),
    MathUtils.randFloat(-10, 10),
    MathUtils.randFloat(-10, 10)
  );
  
  mesh.velocity = new THREE.Vector3(
    MathUtils.randFloat(-0.05, 0.05),
    MathUtils.randFloat(-0.05, 0.05),
    MathUtils.randFloat(-0.05, 0.05)
  );
  
  scene.add(mesh);
  particles.push(mesh);
}

function animate() {
  requestAnimationFrame(animate);

  particles.forEach((particle)=>{
    particle.position.add(particle.velocity);
    
    if(particle.position.x > 10 || particle.position.x < -10){
      particle.velocity.x = -particle.velocity.x;
    }
    
    if(particle.position.y > 10 || particle.position.y < -10){
      particle.velocity.y = -particle.velocity.y;
    }
    
    if(particle.position.z > 10 || particle.position.z < -10){
      particle.velocity.z = -particle.velocity.z;
    }
  });

  renderer.render(scene, camera);
}

animate();

此示例中创建了100个具有随机位置、速度和颜色的粒子,并在动画中更新了它们的位置。使用MathUtils.randFloat方法生成随机值。