three Object3D 介绍

92 阅读1分钟

Object3D 是什么有什么作用

  • Object3D 是一个THREE的 API
  • 能在这个API新建的对象中添加物体
  • 物体会想对于 Object3D 的句柄做偏移,旋转 ...

使用示例


<template>
    <div id="parkingLot" ref="parkingLot">
    </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import * as THREE from 'three';
const parkingLot = ref();


onMounted(() => {
    const DOMEl = parkingLot.value;
    // 获取 DOMEl 的宽度和高度,以设置渲染器的大小。
    const width = DOMEl.clientWidth;
    const height = DOMEl.clientHeight;


    const renderer = new THREE.WebGLRenderer();
    renderer.setSize( width, height );
    DOMEl.appendChild( renderer.domElement );
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 2000 );
    camera.position.set( 0, 300, 800 );
    camera.lookAt( 0, 0, 0 );


    // 创建一个立方体网格
    const geometry = new THREE.BoxGeometry(100,100,100);
    const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
    const cube = new THREE.Mesh(geometry, material);

    // 创建一个空的 Object3D 对象
    const object3DContainer = new THREE.Object3D();

    // 将立方体添加到 Object3D 对象中
    object3DContainer.add(cube);

    // 设置 Object3D 对象的位置、旋转和缩放
    object3DContainer.position.set(1, 2, 3);
    object3DContainer.rotation.set(Math.PI / 4, Math.PI / 4, 0);
    object3DContainer.scale.set(2, 2, 2);

    // 将 Object3D 对象添加到场景中
    scene.add(object3DContainer);
    // 创建光源
    const light = new THREE.DirectionalLight(0x0000ff, 10);
    light.position.set(10, 10, 10);
    light.castShadow = true;
    scene.add(light);

// 渲染场景
function animate() {
    requestAnimationFrame(animate);
    
    // 旋转 Object3D 对象
    object3DContainer.rotation.y += 0.01;
    
    renderer.render(scene, camera);
}
animate();

});
</script>
<style lang="scss" scoped="scoped">

    #parkingLot {
        width: 940px;
        height: 940px;
        border: 1px solid #ccc;
        margin: 30px auto;
    }

</style>