前言
基本效果如下
一、注意
本实例是基于你己经建立好场景,相机,灯光。
二、使用步骤
1.定义全局变量
首先在data中添加
p : [new THREE.Vector3(-6, 0, -5),new THREE.Vector3(-6, 0, -100),new THREE.Vector3(-6, 0, -300),new THREE.Vector3(-6, 0, -400),new THREE.Vector3(-6, 0, -500)], //要分解的所有坐标
mesh:null,//此为移动物体
points:null,//此为物体移动坐标
_lineA:null,//轨迹线
2.核心代码
注:由于没有跟后台去连接,读取后台数据,本次使用随机坐标,后期的后台数据处理可以根据现有的修改
随机坐标代码如下:
//自动生成坐标
zuobiao(){
let i = 0
var p = [
new THREE.Vector3(0, 10, 0),
new THREE.Vector3(-6, 10, -5),
//console.log(this.AA),
new THREE.Vector3(-6, 10, -100),].slice(-2,i)
let yi = -20 ;
let xi = -120
setTimeout(() => {
this.timer=setInterval(() => {
var test = [1,2,3,4,5,6,7,8,9,10,11,12]
var testa = test.splice(i,3)
//console.log(testa)
//console.log(i)
var pp = p.slice(-3,i)
console.log(p)
console.log(pp)
var curve = new THREE.CatmullRomCurve3(p, false/*是否闭合*/);
//this.points = curve.getPoints(500);
var suijishux = Math.round(Math.random()*(100-80))
var suijishuy = Math.round(Math.random()*(100-70))
p.push(new THREE.Vector3(yi, 10, xi))
this.points = curve.getPoints(500);
i+=2
yi+=suijishuy;
xi+=suijishux;
//if(yi>100) {yi-=300;xi-=300}
},1000)
},0)
},
运动代码如下:
ShowLine(){
var box = new THREE.BoxGeometry(5, 5, 5);
var material = new THREE.MeshLambertMaterial({
color: 0x000099
}); //材质对象
this.mesh = new THREE.Mesh(box, material);
this.scene.add(this.mesh);
//mesh.position.set(0, 0, 0)
var curve = new THREE.CatmullRomCurve3(this.p, false/*是否闭合*/);
var points = curve.getPoints(100);
console.log(points)
var _material = new THREE.LineBasicMaterial({
color: 0xff0000
});
var _geometry = new THREE.BufferGeometry();
var _pointsBuf = [
//10,0,0,
//0,0,10,
]
console.log(_pointsBuf)
var _vertices = new Float32Array(_pointsBuf);
_geometry.addAttribute('position', new THREE.BufferAttribute(_vertices, 3));
this._lineA = new THREE.Line(_geometry, _material);
// this.scene.add(this._lineA);
let _i = 0;;
setTimeout(() => {
this.timera=setInterval(() => {
_pointsBuf.push(this.points[_i].x, this.points[_i].y, this.points[_i].z)
_vertices = new Float32Array(_pointsBuf)
_geometry.addAttribute('position', new THREE.BufferAttribute(_vertices, 3));
this.mesh.position.set(this.points[_i].x, this.points[_i].y, this.points[_i].z);
this.mesh.lookAt(this.points[_i+1].x, this.points[_i+1].y, this.points[_i+1].z)
_i++;
//if(_i>100-1)_i=0 ; //原来为_i=0,没有{return} {return;}
}, 60 );
}, 0);
},
注意:每次记着清除计时器,要先在data中定义定时器timer和timera,并且还要清除data中的points
//关闭定时器函数
beforeDestroy() {
clearInterval(this.timer);
this.timer = null;
clearInterval(this.timera);
this.timera = null;
}