59 lines
2.3 KiB
TypeScript
59 lines
2.3 KiB
TypeScript
import { _decorator, Component, CameraComponent, Node, Vec3, tween, geometry, MeshRenderer } from 'cc';
|
||
const { ccclass, property } = _decorator;
|
||
|
||
@ccclass('CameraMover')
|
||
export class CameraMover extends Component {
|
||
@property({ type: CameraComponent })
|
||
public camera: CameraComponent | null = null;
|
||
|
||
@property
|
||
public transitionTime: number = 1.0; // Время анимации
|
||
|
||
public moveToTarget(target: Node) {
|
||
if (!this.camera) {
|
||
console.warn('🚨 Камера не найдена!');
|
||
return;
|
||
}
|
||
|
||
|
||
const meshRenderer = target.getComponent(MeshRenderer);
|
||
if (!meshRenderer) {
|
||
console.warn(`⚠️ У объекта ${target.name} нет MeshRenderer!`);
|
||
return;
|
||
}
|
||
|
||
// Создаем AABB (Axis-Aligned Bounding Box)
|
||
const aabb = new geometry.AABB();
|
||
meshRenderer.model?.updateWorldBound(); // Обновляем границы
|
||
if (meshRenderer.model?.worldBounds) {
|
||
aabb.copy(meshRenderer.model.worldBounds);
|
||
} else {
|
||
console.warn(`⚠️ Не удалось получить worldBounds у ${target.name}`);
|
||
return;
|
||
}
|
||
|
||
// Получаем центр объекта
|
||
const center = aabb.center.clone();
|
||
|
||
// Получаем размеры объекта (умножаем halfExtents на 2)
|
||
const size = aabb.halfExtents.clone().multiplyScalar(2);
|
||
const maxDim = Math.max(size.x, size.y, size.z);
|
||
|
||
// Вычисляем расстояние камеры до объекта
|
||
const fov = this.camera.fov * (Math.PI / 180);
|
||
const distance = maxDim / (2 * Math.tan(fov / 2)) + 5;
|
||
|
||
// Получаем текущее направление камеры
|
||
const direction = this.camera.node.forward.negative();
|
||
const newPosition = center.clone().add(direction.multiplyScalar(distance));
|
||
|
||
console.log(`🎥 Перемещение камеры к ${target.name}`);
|
||
|
||
// Анимируем перемещение камеры
|
||
tween(this.camera.node)
|
||
.to(this.transitionTime, { position: newPosition })
|
||
.call(() => this.camera?.node.lookAt(center))
|
||
.start();
|
||
}
|
||
}
|