threejs的控制器 立方体空间 基本控制器+惯性控制+飞行控制
import React, {Component} from 'react';
import * as THREE from "three";
import {OrbitControls} from "three/examples/jsm/controls/OrbitControls";
import {TrackballControls} from "three/examples/jsm/controls/TrackballControls";
import {FlyControls} from "three/examples/jsm/controls/FlyControls";
const clock=new THREE.Clock()
class Index extends Component {
ready:false
constructor(args) {
super(args);
this.state={
width:window.innerWidth,
height:window.innerHeight,
count:0,
}
this.ballpoi={
x:0,
y:100,
z:0,
vx:(Math.random()-0.5)*7,
vy:(Math.random()-0.5)*7,
vz:(Math.random()-0.5)*7
}
}
render() {
return (
<div className={'three-canvas'}>
</div>
);
}
componentDidMount() {
if(this.state.count===0){
this.init()
this.state.count++
}
}
getRenderer(){
const renderer=new THREE.WebGLRenderer()
renderer.setSize(this.state.width,this.state.height)
document.querySelector('.three-canvas').appendChild(renderer.domElement)
return renderer
}
getCamera(){
const camera=new THREE.PerspectiveCamera(75,this.state.width/this.state.height,1,1000)
camera.position.z=400
camera.lookAt(0,0,0)
return camera
}
getScene(){
const scene=new THREE.Scene()
return scene
}
getControl(){
const control=new FlyControls(this.camera,this.renderer.domElement)
control.movementSpeed=50
control.autoForward =false
control.rollSpeed=0.5
return control
}
addLight(){
const light = new THREE.AmbientLight( 0xffffff,0.5);
const pointLight = new THREE.PointLight( 0xffffff,1);
pointLight.position.set(0,0,0)
pointLight.castShadow=true
this.scene.add( light ,pointLight);
}
addPlane(){
const geometry=new THREE.BoxGeometry(Math.random()*10,Math.random()*10,Math.random()*10)
const material = new THREE.MeshNormalMaterial({side: THREE.DoubleSide})
const box= new THREE.Mesh(
geometry,
material
)
box.rotation.set(Math.PI/(Math.random()*10),Math.PI/(Math.random()*10),Math.PI/(Math.random()*10))
box.position.set((Math.random()-0.5)*300,(Math.random()-0.5)*300,(Math.random()-0.5)*300)
this.scene.add(box)
return box
}
init(){
this.renderer=this.getRenderer()
this.camera=this.getCamera()
this.scene=this.getScene()
this.scene.background=new THREE.Color('#d1b8b8')
for (let i=0;i<400;i++){
this.addPlane()
}
this.addLight()
this.control=this.getControl()
this.animation()
}
animation(){
requestAnimationFrame(this.animation.bind(this))
this.renderer.render(this.scene,this.camera)
this.control.update(clock.getDelta())
}
}
export default Index;