用html写一个three.js中让多个物体运动相互关联代码
时间: 2024-01-29 17:04:17 浏览: 126
JavaScript实现多个物体同时运动
以下是一个使用HTML和Three.js库创建多个相互关联运动物体的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Three.js Multiple Objects Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>
<style>
body {
margin: 0;
}
canvas {
display: block;
}
</style>
</head>
<body>
<script>
// 初始化场景、相机、渲染器
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建多个物体并添加到场景中
var geometry1 = new THREE.BoxGeometry(1, 1, 1);
var material1 = new THREE.MeshBasicMaterial({color: 0xff0000});
var cube1 = new THREE.Mesh(geometry1, material1);
scene.add(cube1);
var geometry2 = new THREE.BoxGeometry(1, 1, 1);
var material2 = new THREE.MeshBasicMaterial({color: 0x00ff00});
var cube2 = new THREE.Mesh(geometry2, material2);
scene.add(cube2);
var geometry3 = new THREE.BoxGeometry(1, 1, 1);
var material3 = new THREE.MeshBasicMaterial({color: 0x0000ff});
var cube3 = new THREE.Mesh(geometry3, material3);
scene.add(cube3);
// 设置物体初始位置
cube1.position.x = -2;
cube2.position.x = 0;
cube3.position.x = 2;
// 创建一个关联运动函数,使物体跟随鼠标移动
function followMouse(event) {
// 计算鼠标在屏幕中的坐标
var mouseX = event.clientX - window.innerWidth/2;
var mouseY = event.clientY - window.innerHeight/2;
// 将物体的位置与鼠标位置关联
cube1.position.x = -mouseX/100;
cube2.position.x = 0;
cube3.position.x = mouseX/100;
cube1.position.y = mouseY/100;
cube2.position.y = -mouseY/100;
cube3.position.y = mouseY/100;
}
// 监听鼠标移动事件
window.addEventListener('mousemove', followMouse, false);
// 渲染场景
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```
该代码将创建三个不同颜色的立方体,并使用鼠标移动事件将它们关联在一起。当鼠标在屏幕上移动时,立方体将跟随鼠标移动,并且它们之间的位置关系将保持不变。您可以根据需要更改物体的数量、位置和关联方式。
阅读全文