涉及到模拟鸟类飞行的状态,首先需要模拟鸟类的形态,代码如下:
var Bird = function () {
var scope = this;
THREE.Geometry.call(this);
v(5, 0, 0);
v(-5, -2, 1);
v(-5, 0, 0);
v(-5, -2, -1);
v(0, 2, -6);
v(0, 2, 6);
v(2, 0, 0);
v(-3, 0, 0);
f3(0, 2, 1);
f3(4, 7, 6);
f3(5, 6, 7);
this.computeFaceNormals();
function v(x, y, z) {
scope.vertices.push(new THREE.Vector3(x, y, z));
}
function f3(a, b, c) {
scope.faces.push(new THREE.Face3(a, b, c));
}
}
Bird.prototype = Object.create(THREE.Geometry.prototype);
Bird.prototype.constructor = Bird;
模拟出鸟类的样式。
同样需要模拟动态的鸟类飞行的状态,代码如下:
var Boid = function () {
var vector = new THREE.Vector3();
//加速
var _acceleration;
//宽度
var _width = 500;
//高度
var _height = 500;
//深度
var _depth = 200;
var _goal;
//相邻之间的距离
var _neighborhoodRedius = 100;
//最大速度
var _maxSpeed = 4;
var _maxSteerForce = 0.1;
//场景中是否有障碍
var _avoidWalls = false;
//位置
this.position = new THREE.Vector3();
//速率
this.velocity = new THREE.Vector3();
//加速
_acceleration = new THREE.Vector3();
//属性赋值
this.setGoal = function (target) {
_goal = target;
};
this.setAvoidWalls = function (value) {
_avoidWalls = value;
};
this.setWorldSize = function (width, height, depth) {
_width = width;
_height = height;
_depth = depth;
};
//运行
this.run = function (boids) {
if (_avoidWalls) {
vector.set(-_width, this.position.y, this.position.z);
vector = this.avoid(vector);
//vector中的xyz矩阵相乘倍数5 x=1 y=1 z=1 结果之后是 x=5 y=5 z=5
vector.multiplyScalar(5);
_acceleration.add(vector);
vector.set(_width, this.position.y, this.position.z);
vector = this.avoid(vector);
vector.multiplyScalar(5);
_acceleration.add(vector);
vector.set(this.position.x, -_height, this.position.z);
vector = this.avoid(vector);