从Unity到Three.js(计时器、Transform)

计时器、模型对象平移函数、枚举定义的使用

对应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();
相关推荐
陪我一起学编程31 分钟前
创建Vue项目的不同方式及项目规范化配置
前端·javascript·vue.js·git·elementui·axios·企业规范
Summer不秃1 小时前
uniapp 手写签名组件开发全攻略
前端·javascript·vue.js·微信小程序·小程序·html
coderklaus2 小时前
Base64编码详解
前端·javascript
浮桥2 小时前
vue3 - 组件间的传值
前端·javascript·vue.js
wuzuyu3652 小时前
生成一个竖直放置的div,宽度是350px,上面是标题固定高度50px,下面是自适应高度的div,且有滚动条
前端·javascript·css
GISer_Jinger4 小时前
Trae Solo模式生成一个旅行足迹App
前端·javascript
zhangbao90s4 小时前
Intl API:浏览器原生国际化API入门指南
前端·javascript·html
s3xysteak4 小时前
我要成为vue高手02:数据传递
前端·javascript·vue.js
文艺理科生5 小时前
Nuxt 状态管理权威指南:从 useState 到 Pinia
前端·javascript·vue.js
汪子熙5 小时前
解决 Node.js 无法获取本地颁发者证书问题的详细分析与代码示例
javascript·后端