sdfsdf

import { useEffect, useRef } from 'react';
import * as THREE from 'three';
import { generateRobot, generateStarts } from './generate';
import { ThreeTool } from './ThreeTool';
import Stats from 'three/examples/jsm/libs/stats.module.js';

/**
 * 创建一个Three.js场景,包括相机和渲染器
 */
function ThreeJs() {
    // 创建一个div容器,用于存放渲染的Three.js场景
    const containerRef = useRef<HTMLDivElement>(null);
    const statsRef = useRef<Stats>(); // 创建用于引用统计信息的 ref

    // 创建 ThreeTool 实例
    const instance = new ThreeTool();

    // 初始化相机位置和朝向
    instance.camera.position.set(15, 12, 8);
    instance.camera.lookAt(0, 0, 0);

    // 添加坐标系
    instance.initAxisHelper();

    // 设置hdr背景图
    instance.initSky('./DayEnvironment_2K.hdr');

    // 生成机器人和星星(模型)
    const robot = generateRobot();
    const robot2 = generateRobot();
    robot2.position.x = 10;
    robot2.position.z = 6;
    const starts = generateStarts(200);

    // 将物体添加到场景
    instance.scene.add(robot, robot2, starts);

    // 创建并设置方向光
    const straightLight = new THREE.DirectionalLight(0xffffff, 5);
    straightLight.position.set(20, 20, 20);
    instance.scene.add(straightLight);
    // 动画函数
    const animate = () => {
        requestAnimationFrame(animate);
        robot.rotation.z -= 0.005;
        robot2.rotation.y -= 0.005;
        starts.rotation.y -= 0.001;
        starts.rotation.z += 0.001;
        starts.rotation.x += 0.001;
        instance.renderer.render(instance.scene, instance.camera);
        statsRef.current && statsRef.current.update(); // 更新统计信息
    };

    // 监听组件挂载和卸载
    useEffect(() => {
        if (containerRef.current) {
            containerRef.current.appendChild(instance.renderer.domElement);
            instance.renderer.render(instance.scene, instance.camera);
            statsRef.current = instance.initStats(containerRef.current); // 初始化统计信息
            // 启动动画循环
            animate();
        }
    }, [containerRef]);

    // 返回div容器,用于存放渲染的Three.js场景
    return <div ref={containerRef} style={{ width: '100vw', height: '100vh' }}></div>;
}

// 导出Robot组件
export default ThreeJs;

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小杜的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值