three.js-让物体动起来
three.js-让物体动起来
三维物体(Object3D)
这是Three.js中大部分对象的基类,提供了一系列的属性和方法来对三维空间中的物体进行操纵。
请注意,可以通过.add( object )方法来将对象进行组合,该方法将对象添加为子对象,但为此最好使用Group(来作为父对象)。
构造器
Object3D()
构造器中不带有参数。
1.设置物体移动-position
import * as THREE from "three";
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
// 位置
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry(2, 2, 2);
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
// 移动物体
cube.position.set(1,0,0);
scene.add(cube);
camera.position.z = 5;
const controls = new OrbitControls( camera, renderer.domElement );
const axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );
function render() {
if (cube.position.x >= 5) {
cube.position.x = 0;
}
cube.position.x += 0.01;
renderer.render(scene, camera);
requestAnimationFrame(render);
}
render();
2.设置物体缩放和旋转-scale-rotation
import * as THREE from "three";
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
// 旋转和缩放
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry(2, 2, 2);
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
cube.position.set(1,0,0);
cube.scale.set(0.5,0.5,0.5);
cube.rotation.set(Math.PI / 4, 0, 0, 'XYZ')
scene.add(cube);
camera.position.z = 5;
const controls = new OrbitControls( camera, renderer.domElement );
const axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );
function render() {
cube.rotation.x += 0.1;
if (cube.position.x >= 5) {
cube.position.x = 0;
}
cube.position.x += 0.01;
renderer.render(scene, camera);
requestAnimationFrame(render);
}
render();
展示效果:自行试验