使用 Three.js 创建一个 3D 人形机器人仿真系统

ops/2024/12/28 13:00:52/

引言

在这篇文章中,我们将探讨如何使用 Three.js 创建一个简单但有趣的 3D 人形机器人仿真系统。这个机器人可以通过键盘控制进行行走和转向,并具有基本的动画效果。

在这里插入图片描述

技术栈

  • HTML5
  • Three.js
  • JavaScript

实现步骤

1. 基础设置

首先,我们需要创建基本的 HTML 结构并引入 Three.js 库:

<!DOCTYPE html>
<html>
<head><title>3D Robot Simulation</title><style>body { margin: 0; overflow: hidden;}canvas { display: block; }#info {position: absolute;top: 10px;left: 10px;color: white;font-family: Arial;font-size: 14px;background: rgba(0,0,0,0.5);padding: 10px;}</style>
</head>
<body><div id="info">使用方向键控制机器人:<br>↑ - 向前移动<br>← → - 左右转向</div><script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
</body>
</html>

2. 场景初始化

接下来,我们需要初始化 Three.js 的基本组件:

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x87CEEB); // 天空蓝色背景const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);

3. 创建机器人类

创建一个 Robot 类来管理机器人的所有组件和动作:

class Robot {constructor() {this.body = new THREE.Group();// 创建躯干const torsoGeometry = new THREE.BoxGeometry(2, 3, 1);const torsoMaterial = new THREE.MeshPhongMaterial({color: 0x999999});this.torso = new THREE.Mesh(torsoGeometry, torsoMaterial);this.torso.castShadow = true;// 创建头部const headGeometry = new THREE.SphereGeometry(0.5);const headMaterial = new THREE.MeshPhongMaterial({color: 0xcccccc});this.head = new THREE.Mesh(headGeometry, headMaterial);this.head.position.y = 2;this.head.castShadow = true;// ... 其他部件的创建代码 ...}// 创建四肢createLimb(width, height) {const geometry = new THREE.BoxGeometry(width, height, width);const material = new THREE.MeshPhongMaterial({color: 0x999999});const limb = new THREE.Mesh(geometry, material);limb.castShadow = true;return limb;}// 行走动画walk() {const legRotation = Math.sin(Date.now() * 0.005) * 0.5;this.leftLeg.rotation.x = legRotation;this.rightLeg.rotation.x = -legRotation;const armRotation = Math.sin(Date.now() * 0.005) * 0.25;this.leftArm.rotation.x = -armRotation;this.rightArm.rotation.x = armRotation;}// 转向和移动方法turn(angle) {this.body.rotation.y += angle;}moveForward(speed) {this.body.position.x += Math.sin(this.body.rotation.y) * speed;this.body.position.z += Math.cos(this.body.rotation.y) * speed;}
}

4. 添加环境元素

创建地面和光照系统:

// 创建地面
const groundGeometry = new THREE.PlaneGeometry(100, 100);
const groundMaterial = new THREE.MeshPhongMaterial({ color: 0x808080,side: THREE.DoubleSide
});
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -2.5;
ground.receiveShadow = true;
scene.add(ground);// 添加光源
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(5, 10, 5);
directionalLight.castShadow = true;
scene.add(directionalLight);const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);

5. 实现控制系统

添加键盘控制和动画循环:

const keyStates = {};document.addEventListener('keydown', (e) => {keyStates[e.key] = true;
});document.addEventListener('keyup', (e) => {keyStates[e.key] = false;
});function animate() {requestAnimationFrame(animate);if(keyStates['ArrowUp']) {robot.walk();robot.moveForward(0.1);}if(keyStates['ArrowLeft']) {robot.turn(0.05);}if(keyStates['ArrowRight']) {robot.turn(-0.05);}camera.position.x = robot.body.position.x;camera.position.z = robot.body.position.z + 10;camera.lookAt(robot.body.position);renderer.render(scene, camera);
}animate();

主要特性

  1. 3D 人形机器人模型
  2. 基本的行走动画
  3. 键盘控制系统
  4. 相机跟随
  5. 阴影效果
  6. 响应式设计

控制方法

  • ↑ 向前移动
  • ← 向左转
  • → 向右转

可能的改进方向

  1. 添加更多动作(如后退、跳跃)
  2. 改进机器人模型细节
  3. 添加碰撞检测
  4. 添加物理引擎
  5. 实现更复杂的动画效果
  6. 添加声音效果
  7. 增加更多交互控制选项
  8. 优化性能

结论

通过这个项目,我们展示了如何使用 Three.js 创建一个基本的 3D 人形机器人仿真系统。虽然这是一个相对简单的实现,但它为更复杂的 3D 网页应用提供了良好的起点。

完整代码

<!DOCTYPE html>
<html>
<head><title>3D Robot Simulation</title><style>body { margin: 0; overflow: hidden;}canvas { display: block; }#info {position: absolute;top: 10px;left: 10px;color: white;font-family: Arial;font-size: 14px;background: rgba(0,0,0,0.5);padding: 10px;}</style>
</head>
<body><div id="info">使用方向键控制机器人:<br>- 向前移动<br>← → - 左右转向</div><script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script><script>// 初始化场景、相机和渲染器const scene = new THREE.Scene();scene.background = new THREE.Color(0x87CEEB); // 天空蓝色背景const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);const renderer = new THREE.WebGLRenderer({ antialias: true });renderer.setSize(window.innerWidth, window.innerHeight);renderer.shadowMap.enabled = true;document.body.appendChild(renderer.domElement);// 创建机器人类class Robot {constructor() {// 机器人主体this.body = new THREE.Group();// 躯干const torsoGeometry = new THREE.BoxGeometry(2, 3, 1);const torsoMaterial = new THREE.MeshPhongMaterial({color: 0x999999});this.torso = new THREE.Mesh(torsoGeometry, torsoMaterial);this.torso.castShadow = true;// 头部const headGeometry = new THREE.SphereGeometry(0.5);const headMaterial = new THREE.MeshPhongMaterial({color: 0xcccccc});this.head = new THREE.Mesh(headGeometry, headMaterial);this.head.position.y = 2;this.head.castShadow = true;// 眼睛const eyeGeometry = new THREE.SphereGeometry(0.1);const eyeMaterial = new THREE.MeshPhongMaterial({color: 0x000000});this.leftEye = new THREE.Mesh(eyeGeometry, eyeMaterial);this.rightEye = new THREE.Mesh(eyeGeometry, eyeMaterial);this.leftEye.position.set(-0.2, 2, 0.4);this.rightEye.position.set(0.2, 2, 0.4);// 手臂this.leftArm = this.createLimb(0.3, 2);this.leftArm.position.set(-1.2, 1, 0);this.rightArm = this.createLimb(0.3, 2);this.rightArm.position.set(1.2, 1, 0);// 腿部this.leftLeg = this.createLimb(0.4, 2);this.leftLeg.position.set(-0.6, -1.5, 0);this.rightLeg = this.createLimb(0.4, 2);this.rightLeg.position.set(0.6, -1.5, 0);// 组装机器人this.body.add(this.torso);this.body.add(this.head);this.body.add(this.leftEye);this.body.add(this.rightEye);this.body.add(this.leftArm);this.body.add(this.rightArm);this.body.add(this.leftLeg);this.body.add(this.rightLeg);}createLimb(width, height) {const geometry = new THREE.BoxGeometry(width, height, width);const material = new THREE.MeshPhongMaterial({color: 0x999999});const limb = new THREE.Mesh(geometry, material);limb.castShadow = true;return limb;}walk() {// 腿部摆动const legRotation = Math.sin(Date.now() * 0.005) * 0.5;this.leftLeg.rotation.x = legRotation;this.rightLeg.rotation.x = -legRotation;// 手臂摆动const armRotation = Math.sin(Date.now() * 0.005) * 0.25;this.leftArm.rotation.x = -armRotation;this.rightArm.rotation.x = armRotation;}turn(angle) {this.body.rotation.y += angle;}moveForward(speed) {this.body.position.x += Math.sin(this.body.rotation.y) * speed;this.body.position.z += Math.cos(this.body.rotation.y) * speed;}}// 创建地面const groundGeometry = new THREE.PlaneGeometry(100, 100);const groundMaterial = new THREE.MeshPhongMaterial({ color: 0x808080,side: THREE.DoubleSide});const ground = new THREE.Mesh(groundGeometry, groundMaterial);ground.rotation.x = -Math.PI / 2;ground.position.y = -2.5;ground.receiveShadow = true;scene.add(ground);// 创建机器人实例const robot = new Robot();scene.add(robot.body);// 添加光源const directionalLight = new THREE.DirectionalLight(0xffffff, 1);directionalLight.position.set(5, 10, 5);directionalLight.castShadow = true;directionalLight.shadow.camera.near = 0.1;directionalLight.shadow.camera.far = 100;directionalLight.shadow.camera.left = -50;directionalLight.shadow.camera.right = 50;directionalLight.shadow.camera.top = 50;directionalLight.shadow.camera.bottom = -50;scene.add(directionalLight);const ambientLight = new THREE.AmbientLight(0x404040);scene.add(ambientLight);// 设置相机位置camera.position.set(0, 5, 10);camera.lookAt(robot.body.position);// 键盘状态const keyStates = {};// 键盘事件监听document.addEventListener('keydown', (e) => {keyStates[e.key] = true;});document.addEventListener('keyup', (e) => {keyStates[e.key] = false;});// 窗口大小调整window.addEventListener('resize', onWindowResize, false);function onWindowResize() {camera.aspect = window.innerWidth / window.innerHeight;camera.updateProjectionMatrix();renderer.setSize(window.innerWidth, window.innerHeight);}// 动画循环function animate() {requestAnimationFrame(animate);// 更新机器人动作if(keyStates['ArrowUp']) {robot.walk();robot.moveForward(0.1);}if(keyStates['ArrowLeft']) {robot.turn(0.05);}if(keyStates['ArrowRight']) {robot.turn(-0.05);}// 相机跟随camera.position.x = robot.body.position.x;camera.position.z = robot.body.position.z + 10;camera.lookAt(robot.body.position);renderer.render(scene, camera);}animate();</script>
</body>
</html>

http://www.ppmy.cn/ops/145661.html

相关文章

2024基于大模型的智能运维(附实践资料合集)

基于大模型的智能运维是指利用人工智能技术&#xff0c;特别是大模型技术&#xff0c;来提升IT运维的效率和质量。以下是一些关键点和实践案例&#xff1a; AIOps的发展&#xff1a;AIOps&#xff08;人工智能在IT运维领域的应用&#xff09;通过大数据分析和机器学习技术&…

代码随想录Day49 42. 接雨水,84.柱状图中最大的矩形。

1.接雨水 力扣题目链接(opens new window) 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图&#xff0c;计算按此排列的柱子&#xff0c;下雨之后能接多少雨水。 示例 1&#xff1a; 输入&#xff1a;height [0,1,0,2,1,0,1,3,2,1,2,1]输出&#xff1a;6解释&#xff1a…

自动驾驶AVM环视算法--python版本的车轮投影模式

c语言版本和算法原理的可以查看本人的其他文档。《自动驾驶AVM环视算法--超广角模式/转向模式/3D碗型投影模式/窄边模式/车轮模式等的实现》本文档进用于展示部分代码的视线&#xff0c;获取方式网盘自行获取&#xff08;非免费介意勿下载&#xff09;&#xff1a;链接: https:…

arcgis server ip修改后服务异常解决方案

1、停止arcgisserver ./home/geoscene/geoscene/server/stopserver.sh 2、修改数据库注册文件 a、进入目录&#xff1a;/home/geoscene/geoscene/server/usr/config-store/data/enterpriseDatabases/sde b、修改文件dataItem.json&#xff1a;将所有IP修改为最新IP 3…

使用c#制作坐标

1、建立坐标 2、坐标系的放大缩小 3、标定刻度 4、实时显示鼠标在坐标系上的坐标 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using S…

Cornerstone3d 基础概念

基础Cornerstone流程&#xff1a; 获取ImageId。通过Image Loader使用ImageId得到Image Object。通过Rendering Engine使用Image Object渲染到视口Viewports。 ImageId 简介&#xff1a;ImageId是一个URL&#xff0c;用于标识单张图片。 ImageId格式&#xff1a; Image Load…

Android Https和WebView

系统会提示说不安全&#xff0c;因为网站通过js就能调用你的android代码&#xff0c;如果你确认你的网站没用到JS的话就不要打开这个开关&#xff0c;如果用到了&#xff0c;就添加一个注解忽略它就行了。 后来就使用我们公司的网站了&#xff0c;发现也出不来&#xff0c;后来…

云计算时代携程的网络架构变迁

大家觉得有意义和帮助记得及时关注和点赞!!! 前言0 携程云平台简介 网络演进时间线1 基于 VLAN 的二层网络 1.1 需求1.2 解决方案&#xff1a;OpenStack Provider Network 模型1.3 硬件网络拓扑1.4 宿主机内部网络拓扑1.5 小结 优点缺点2 基于 SDN 的大二层网络 2.1 面临的新问…