yantar/assets/Scripts/CameraMover.ts

59 lines
2.3 KiB
TypeScript
Raw Permalink 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 { _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();
}
}