从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();
相关推荐
YHHLAI6 分钟前
React `useState` 深入浅出
前端·javascript·react.js
Behaviour13 分钟前
Unity游戏之Jenkins的安装部署应用
游戏·unity·jenkins
半个落月24 分钟前
用 Harness 工程化缓解 LLM 幻觉:Best of N Sampling + LLM as Judge 实战
javascript·人工智能
三十而立洋28 分钟前
从 0 到 1:我用 VS Code API + Git 命令写了一个"代码统计"插件
javascript
云浪1 小时前
如何让大模型操作 MySQL 数据库?
javascript·人工智能·后端
大Mod_abfun2 小时前
Unity案例10-水晶矿石碰撞碎裂案例
unity·游戏引擎
lilian2332 小时前
Harmony os 技术实战|拼豆制图46:图片解码失败为何不能悄悄返回示例图
前端·javascript·华为·harmonyos
xcLeigh3 小时前
Unity基础:Input输入系统入门——键盘、鼠标与触摸检测
unity·计算机外设·游戏引擎
threerocks11 小时前
AI 原生软件开发生命周期手册 - 如何借助 AI,逐阶段改造软件开发生命周期
前端·javascript·后端
ly768912 小时前
JavaScript 从入门到进阶:核心语法、异步编程与工程化实践
开发语言·javascript·ecmascript