有了group,我们可以实现一个会动的小人出来了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script>
</head>
<body>
<div id="webgl"></div>
</body>
</html>
<script>
var axes = new THREE.AxesHelper(200);//50表示xyz轴的长度,红:x,绿:y,蓝:z
var scene = new THREE.Scene();
var ambient = new THREE.AmbientLight(0xffffff);//环境光
scene.add(ambient); //环境光添加到场景中
// 头部网格模型和组
var headMesh = sphereMesh(10, 0, 0, 0);
headMesh.name = "头"
var leftEyeMesh = sphereMesh(1, 8, 5, 4);
leftEyeMesh.name = "左眼"
var rightEyeMesh = sphereMesh(1, 8, 5, -4);
rightEyeMesh.name = "右眼"
var headGroup = new THREE.Group();
headGroup.name = "头部容器"
headGroup.add(headMesh, leftEyeMesh, rightEyeMesh);//添加多个mesh模型
// 身体网格模型和组
var neckMesh = cylinderMesh(3, 10, 0, -15, 0);
neckMesh.name = "脖子"
var bodyMesh = cylinderMesh(14, 30, 0, -35, 0);
bodyMesh.name = "腹部"
var leftLegMesh = cylinderMesh(4, 60, 0, -80, -7);
leftLegMesh.name = "左腿"
var rightLegMesh = cylinderMesh(4, 60, 0, -80, 7);
rightLegMesh.name = "右腿"
var legGroup = new THREE.Group();
legGroup.name = "腿"
legGroup.add(leftLegMesh, rightLegMesh);
var bodyGroup = new THREE.Group();
bodyGroup.name = "躯干容器"
bodyGroup.add(neckMesh, bodyMesh, legGroup);
// 人Group
var personGroup = new THREE.Group();
personGroup.name = "人体容器"
personGroup.add(headGroup, bodyGroup);
scene.add(personGroup);
// 球体网格模型创建函数
function sphereMesh(R, x, y, z) {
var geometry = new THREE.SphereGeometry(R, 25, 25); //球体几何体
var material = new THREE.MeshLambertMaterial({
color: 0xffff00
}); //材质对象Material
var mesh = new THREE.Mesh(geometry, material); // 创建网格模型对象
mesh.position.set(x, y, z);
return mesh;
}
// 圆柱体网格模型创建函数
function cylinderMesh(R, h, x, y, z) {
var geometry = new THREE.CylinderGeometry(R, R, h, 25, 25); //球体几何体
var material = new THREE.MeshLambertMaterial({
color: 0x00ffff
}); //材质对象Material
var mesh = new THREE.Mesh(geometry, material); // 创建网格模型对象
mesh.position.set(x, y, z);
return mesh;
}
//创建相机对象
var camera = new THREE.PerspectiveCamera(45, 2, 0.1, 2000);
camera.position.set(200, 100, 100); //设置相机位置
camera.lookAt(scene.position); //设置相机方向(指向的场景对象)
/**
* 创建渲染器对象
*/
var renderer = new THREE.WebGLRenderer({
antialias: true //消除锯齿
});
renderer.setSize(1000, 500);//设置渲染区域尺寸
renderer.setClearColor(0xb9d3ff, 1); //设置背景颜色
var cont = document.getElementById('webgl');
cont.appendChild(renderer.domElement);
render();
function render() {
renderer.render(scene, camera);//渲染必须有场景和相机两个对象
personGroup.rotateY(0.1);//作为一个整体旋转
requestAnimationFrame(render);//递归调用
}
</script>
person.gif
网友评论