WEB/src/utils/threeUtils.js
2026-03-16 14:21:04 +08:00

391 lines
10 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import * as THREE from 'three'
// 使用 Three.js 自带的 OrbitControls
let OrbitControls = null
// 异步加载 OrbitControls
export const loadOrbitControls = async () => {
if (typeof window === 'undefined') return null
try {
const module = await import('three/examples/jsm/controls/OrbitControls.js')
OrbitControls = module.OrbitControls
console.log('OrbitControls 加载成功')
return OrbitControls
} catch (error) {
console.warn('无法加载 OrbitControls:', error.message)
return null
}
}
// 辅助函数:厘米转Three.js单位(1单位=1cm)
const cm = (value) => value// Three.js中直接使用厘米为单位
// 俯瞰模式控制器(增强版)
// 漫游模式控制器(第一人称)- 增强版
export class RoamControls {
constructor(camera, domElement, scene) {
this.camera = camera
this.domElement = domElement
this.scene = scene
this.enabled = true
// 漫游参数 - 厘米为单位
this.moveSpeed = cm(30)// 每秒移动30厘米
this.rotateSpeed = 0.002
this.jumpForce = cm(50)
this.gravity = cm(2)
// 移动状态
this.moveForward = false
this.moveBackward = false
this.moveLeft = false
this.moveRight = false
this.moveUp = false
this.moveDown = false
// 视角控制
this.isMouseDown = false
this.lastMouseX = 0
this.lastMouseY = 0
this.yaw = 0
this.pitch = 0
// 物理参数
this.velocity = new THREE.Vector3()
this.onGround = true
this.groundHeight = 0
// 碰撞检测
this.collisionObjects = []
this.raycaster = new THREE.Raycaster()
this.mouse = new THREE.Vector2()
// 点击检测
this.clickableObjects = []// 可点击对象(货架格子)
this.onObjectClick = null// 对象点击回调
// 控制面板
this.showUI = true
this.uiElements = {}
this.initControls()
this.updateCameraRotation()
}
initControls() {
const canvas = this.domElement
// 鼠标控制
const onMouseDown = (e) => {
this.isMouseDown = true
this.lastMouseX = e.clientX
this.lastMouseY = e.clientY
canvas.style.cursor = 'none'
// 请求指针锁定
if (canvas.requestPointerLock) {
canvas.requestPointerLock()
} else if (canvas.mozRequestPointerLock) {
canvas.mozRequestPointerLock()
} else if (canvas.webkitRequestPointerLock) {
canvas.webkitRequestPointerLock()
}
}
const onMouseMove = (e) => {
if (!this.isMouseDown || !this.enabled) return
const movementX = e.movementX || e.mozMovementX || e.webkitMovementX || 0
const movementY = e.movementY || e.mozMovementY || e.webkitMovementY || 0
// 更新视角
this.yaw -= movementX * this.rotateSpeed
this.pitch -= movementY * this.rotateSpeed
// 限制俯仰角度
this.pitch = Math.max(-Math.PI/2, Math.min(Math.PI/2, this.pitch))
this.updateCameraRotation()
}
const onMouseUp = (e) => {
this.isMouseDown = false
canvas.style.cursor = 'grab'
// 退出指针锁定
if (document.exitPointerLock) {
document.exitPointerLock()
} else if (document.mozExitPointerLock) {
document.mozExitPointerLock()
} else if (document.webkitExitPointerLock) {
document.webkitExitPointerLock()
}
// 检测点击对象
if (this.clickableObjects.length > 0 && this.onObjectClick) {
const rect = canvas.getBoundingClientRect()
this.mouse.x = ((e.clientX - rect.left) / rect.width) * 2 - 1
this.mouse.y = -((e.clientY - rect.top) / rect.height) * 2 + 1
this.raycaster.setFromCamera(this.mouse, this.camera)
const intersects = this.raycaster.intersectObjects(this.clickableObjects, true)
if (intersects.length > 0) {
const object = intersects[0].object
let shelfCell = object
// 向上查找带有货架信息的父对象
while (shelfCell && !shelfCell.userData.shelfCellId) {
shelfCell = shelfCell.parent
}
if (shelfCell && shelfCell.userData.shelfCellId) {
this.onObjectClick(
shelfCell.userData.shelfCellId,
shelfCell.userData.shelfRow,
shelfCell.userData.shelfColumn,
shelfCell.userData.shelfLevel
)
}
}
}
}
// 键盘控制
const onKeyDown = (e) => {
switch(e.code){
case 'KeyW':
case 'ArrowUp':
this.moveForward = true
break
case 'KeyS':
case 'ArrowDown':
this.moveBackward = true
break
case 'KeyA':
case 'ArrowLeft':
this.moveLeft = true
break
case 'KeyD':
case 'ArrowRight':
this.moveRight = true
break
case 'Space':
if (this.onGround) {
this.velocity.y = this.jumpForce
this.onGround = false
}
break
case 'ShiftLeft':
case 'ShiftRight':
this.moveDown = true
break
case 'Escape':
// ESC键返回俯瞰模式
if (this.onExitRoam) {
this.onExitRoam()
}
break
}
}
const onKeyUp = (e) => {
switch(e.code){
case 'KeyW':
case 'ArrowUp':
this.moveForward = false
break
case 'KeyS':
case 'ArrowDown':
this.moveBackward = false
break
case 'KeyA':
case 'ArrowLeft':
this.moveLeft = false
break
case 'KeyD':
case 'ArrowRight':
this.moveRight = false
break
case 'ShiftLeft':
case 'ShiftRight':
this.moveDown = false
break
}
}
// 防止右键菜单
canvas.addEventListener('contextmenu', (e) => e.preventDefault())
canvas.addEventListener('mousedown', onMouseDown)
canvas.addEventListener('mousemove', onMouseMove)
canvas.addEventListener('mouseup', onMouseUp)
window.addEventListener('keydown', onKeyDown)
window.addEventListener('keyup', onKeyUp)
// 退出指针锁定时的处理
const onPointerLockChange = () => {
const pointerLockElement =
document.pointerLockElement ||
document.mozPointerLockElement ||
document.webkitPointerLockElement
if (pointerLockElement !== canvas) {
this.isMouseDown = false
canvas.style.cursor = 'grab'
}
}
document.addEventListener('pointerlockchange', onPointerLockChange)
document.addEventListener('mozpointerlockchange', onPointerLockChange)
document.addEventListener('webkitpointerlockchange', onPointerLockChange)
// 保存事件处理器以便清理
this.eventHandlers = {
onMouseDown, onMouseMove, onMouseUp,
onKeyDown, onKeyUp,
onPointerLockChange
}
}
updateCameraRotation() {
this.camera.rotation.order = 'YXZ'
this.camera.rotation.y = this.yaw
this.camera.rotation.x = this.pitch
}
update() {
if (!this.enabled) return
// 计算移动方向
const direction = new THREE.Vector3()
if (this.moveForward) {
direction.z -= 1
}
if (this.moveBackward) {
direction.z += 1
}
if (this.moveLeft) {
direction.x -= 1
}
if (this.moveRight) {
direction.x += 1
}
// 根据相机方向旋转移动向量
direction.applyQuaternion(this.camera.quaternion)
direction.y = 0
direction.normalize()
// 垂直移动
if (this.moveUp) {
direction.y += 1
}
if (this.moveDown) {
direction.y -= 1
}
// 应用移动
this.velocity.x = direction.x * this.moveSpeed
this.velocity.z = direction.z * this.moveSpeed
this.velocity.y = direction.y * this.moveSpeed
// 应用重力(如果不在跳跃状态)
if (!this.onGround) {
this.velocity.y -= this.gravity
}
// 碰撞检测
const newPosition = this.camera.position.clone()
newPosition.x += this.velocity.x
newPosition.z += this.velocity.z
newPosition.y += this.velocity.y
// 简单的边界检查
let canMove = true
for (const obj of this.collisionObjects) {
if (obj.geometry.boundingBox) {
const box = obj.geometry.boundingBox.clone()
box.applyMatrix4(obj.matrixWorld)
// 检查是否与物体碰撞 - 厘米为单位
const playerBox = new THREE.Box3(
new THREE.Vector3(newPosition.x - cm(30), newPosition.y - cm(50), newPosition.z - cm(30)),
new THREE.Vector3(newPosition.x + cm(30), newPosition.y + cm(170), newPosition.z + cm(30))
)
if (box.intersectsBox(playerBox)) {
canMove = false
break
}
}
}
if (canMove) {
this.camera.position.copy(newPosition)
}
// 限制在地面之上 - 厘米为单位
if (this.camera.position.y < this.groundHeight + cm(170)) {
this.camera.position.y = this.groundHeight + cm(170)
this.onGround = true
this.velocity.y = 0
} else {
this.onGround = false
}
}
// 添加可点击对象(货架格子)
addClickableObject(object, shelfCellId, row, column, level) {
object.userData = {
shelfCellId,
shelfRow: row,
shelfColumn: column,
shelfLevel: level,
isClickable: true
}
this.clickableObjects.push(object)
}
// 设置货架格子点击回调
setOnObjectClick(callback) {
this.onObjectClick = callback
}
// 设置退出漫游回调
setOnExitRoam(callback) {
this.onExitRoam = callback
}
addCollisionObject(object) {
this.collisionObjects.push(object)
}
setGroundHeight(height) {
this.groundHeight = height
}
dispose() {
const canvas = this.domElement
const handlers = this.eventHandlers
if (canvas && handlers) {
canvas.removeEventListener('mousedown', handlers.onMouseDown)
canvas.removeEventListener('mousemove', handlers.onMouseMove)
canvas.removeEventListener('mouseup', handlers.onMouseUp)
canvas.removeEventListener('contextmenu', (e) => e.preventDefault())
}
window.removeEventListener('keydown', handlers.onKeyDown)
window.removeEventListener('keyup', handlers.onKeyUp)
document.removeEventListener('pointerlockchange', handlers.onPointerLockChange)
document.removeEventListener('mozpointerlockchange', handlers.onPointerLockChange)
document.removeEventListener('webkitpointerlockchange', handlers.onPointerLockChange)
}
}