创建胶囊物体并实现移动

157 阅读1分钟
class Physics {
    // 创建碰撞世界
    constructor(
        planeGroup, // 需要被检测碰撞的墙体
        scene, // 场景
        camera
    ){
        // 创建八叉树世界
        this.octreeWrold = new Octree()
        // 传入被墙体,创建八叉树节点
        // this.octreeWrold.fromGraphNode(planeGroup)

        // 创建一个人的碰撞体(胶囊)
        this.playerCollider = new Capsule(
            new THREE.Vector3(0,0.35,0),// 圆柱下圆心位置
            new THREE.Vector3(0,1.35,0), // 上圆圆心位置
            0.35 // 上下半圆的半径
        )
        // 加载模型
        const gltfLoader = new GLTFLoader()
        // 创建一个空的3dObject
        this.capsule = new THREE.Object3D()
        this.capsule.position.set(0,0.85,0)
        // 声明动作混合器
        this.mixer = null
        this.actions = []
        // 当前激活的动作
        this.activeAction = null
        gltfLoader.load('path', glb => {
            this.robot = glb.scene
            // 所以许欸
            this.robot.scale.set(0.5,0.5,0.5)
            this.robot.position.set(0,-0.88,0)
            // 将模型add到capsule上面
            this.capsule.add(this.robot)
            // 定义动画混合器
            // this.mixer = new THREE.AnimationMixer(this.robot)
            
            // 加入到场景内
            scene.add(this.capsule)
           
        })
         // 声明另一个相机
            const backCamera = new THREE.PerspectiveCamera(
                70,
                window.innerWidth / window.innerHeight,
                0.001,
                1000
            )
            // 创建一个控制相机上下移动的对象
            this.cameraControl = new THREE.Object3D()
            // 设置两个相机的位置
            camera.position.set(0,2,-5)
            camera.lookAt(this.capsule.position)
            backCamera.position.set(0,2,5)
            backCamera.lookAt(this.capsule.position)
            this.cameraControl.add(camera)
            this.cameraControl.add(backCamera)
            // 将相机控制对象添加到模型胶囊内
            this.capsule.add(this.cameraControl)
            // 通过旋转相机控制对象来操作视角
            document.addEventListener('mousemove',(e)=>{
                // 左右移动鼠标操作模型移动,横向移动鼠标就是模型沿着Y轴旋转
                this.capsule.rotation.y -= e.movementX * 0.003
                // 垂直移动鼠标就是相机控制对象沿着X轴旋转
                this.cameraControl.rotation.x += e.movementY * 0.003
                if(this.cameraControl.rotation.x >  Math.PI / 8){
                    // 限制旋转角度
                    this.cameraControl.rotation.x = Math.PI / 8
                }else if(
                    this.cameraControl.rotation.x < - Math.PI / 8
                ){
                    this.cameraControl.rotation.x = -Math.PI / 8
                }
            })
            // 锁定鼠标
            document.addEventListener('mousedown', e => {
                document.body.requestPointerLock()
            })
            
            // 移动
            // 鼠标状态

    }
}