计时器、模型对象平移函数、枚举定义的使用
对应unity中的一些常用功能
javascript
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(60, 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(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 50;
//枚举定义
const direction = {
UP: '上',
DOWN: '下',
LEFT: '左',
RIGHT: '右'
};
let state;
function changeState(dir) {
console.log("dir=" + dir);
if (state != dir) {
state = dir;
}
}
//计时器
const clock = new THREE.Clock();
let timer = 0;
//枚举索引,不会js的int转枚举语法
let stateIndex = 1;
function updateChangeState() {
timer += clock.getDelta();
if (timer >= 3) {
timer = 0;
stateIndex++;
if (stateIndex == 5) {
stateIndex = 1;
}
changeState(convertToEnum(stateIndex));
}
}
//自定义int转枚举方法
function convertToEnum(value) {
switch (value) {
case 1:
return direction.UP;
case 2:
return direction.LEFT;
case 3:
return direction.DOWN;
case 4:
return direction.RIGHT;
}
}
//更新模型位置
function updateSetObjPosition() {
switch (state) {
case direction.UP:
cube.translateY(0.1);
break;
case direction.DOWN:
cube.translateY(-0.1);
break;
case direction.LEFT:
cube.translateX(-0.1);
break;
case direction.RIGHT:
cube.translateX(0.1);
break;
}
}
function animate() {
requestAnimationFrame(animate);
updateChangeState();
updateSetObjPosition();
renderer.render(scene, camera);
}
animate();