最近在做一个路径规划的例子,大概场景是在一个xy坐标系中,有几个障碍物,一个车要绕过这些障碍物到达目的地,本来用java来实现,但是java调试太不直观了,我就想起用threejs把场景简单搭建出来,规划好的路线也直接展示出来,就可以实时查看路径规划的怎么样了。
先来一张效果图:
首先是添加threejs场景,包括灯光,相机,渲染器,也包括地板,然后得到一个空的场景,为了方便观看,我们把相机调整到地图的正上方,且对准地图的中心点。
initScene(){
this.scene = new THREE.Scene();
const axesHelper = new THREE.AxesHelper( 100 );
axesHelper.position.set(0,0,10)
this.scene.add( axesHelper );
},
initCamera(){
this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000);
this.camera.position.set(200,150,400);
this.camera.lookAt(200,150,0);
// this.camera.up.set(0, 0, 1); // <=== spin // around Z-axis
},
initLight(){
//添加两个平行光
const directionalLight1 = new THREE.DirectionalLight(0xffffff, 1.5);
directionalLight1.position.set(300,300,600)
this.scene.add(directionalLight1);
const directionalLight2 = new THREE.DirectionalLight(0xffffff, 1.5);
directionalLight2.position.set(600,200,600)
this.scene.add(directionalLight2);
},
initFloor(){
let floorGeometry = new THREE.BoxGeometry( this.floor.floorWidth,this.floor.floorLength,this.floor.depth);
let floorMaterial = new THREE.MeshPhysicalMaterial({color:'#FFFFFF'});
let textureFloor = new THREE.TextureLoader().load('/static/images/floor.jpg', function (texture) {
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
})
floorMaterial.map = textureFloor
let floor = new THREE.Mesh( floorGeometry, floorMaterial );
floor.name = '地板';
floor.position.set(this.floor.floorWidth/2,this.floor.floorLength/2,0)
this.scene.add(floor)
},
initRenderer(){
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.container = document.getElementById("container")
this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
this.renderer.setClearColor('#AAAAAA', 1.0);
this.container.appendChild(this.renderer.domElement);
},
initControl(){
this.controls = new OrbitControls(t