yantar/assets/Scripts/ModelSelector.ts
Georgy Shive f2e5fad0f8 исправил логику перемщеения камеры и движжения персонажа,
изменил в размере список ,
добавил логику перемещения на стартовое положение
добавил кнопку для стартового положения
скриптом отрисовал векторную иконку на кнопку
стартового положения
2025-02-19 14:59:18 +07:00

163 lines
6.7 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, Node, CameraComponent, PhysicsSystem, geometry, Vec3, EventMouse, input, Input, tween, MeshRenderer } from 'cc';
import { PulsatingHighlighter } from './PulsatingHighlighter';
import { EquipmentManager } from './stores/EquipmentManager';
const { ccclass, property } = _decorator;
@ccclass('ModelSelector')
export class ModelSelector extends Component {
// Ссылка на камеру, используемую для преобразования координат экрана в луч
@property({ type: CameraComponent })
public camera: CameraComponent | null = null;
private _ray = new geometry.Ray();
private _clickCount = 0;
private _doubleClickThreshold = 0.3; // 300 мс между кликами
onLoad() {
input.on(Input.EventType.MOUSE_UP, this._onMouseUp, this);
}
onDestroy() {
input.off(Input.EventType.MOUSE_UP, this._onMouseUp, this);
}
private _onMouseUp(event: EventMouse) {
// Используем правую кнопку мыши
if (event.getButton() !== 2) return;
console.log('🖱 Правый клик зафиксирован!');
this.unschedule(this._resetClickCount);
this._clickCount++;
if (this._clickCount === 2) {
console.log('✅ Двойной клик зафиксирован!');
this._performRaycast(event);
this._clickCount = 0;
} else {
this.scheduleOnce(this._resetClickCount, this._doubleClickThreshold);
}
}
private _resetClickCount() {
this._clickCount = 0;
console.log('⏳ Сброс двойного клика из-за таймаута.');
}
private _performRaycast(event: EventMouse) {
if (!this.camera) {
console.warn('🚨 Камера не найдена!');
return;
}
const screenPos = new Vec3(event.getLocationX(), event.getLocationY(), 0);
this.camera.screenPointToRay(screenPos.x, screenPos.y, this._ray);
console.log('🔍 Запускаем raycast...');
if (PhysicsSystem.instance.raycast(this._ray)) {
const results = PhysicsSystem.instance.raycastResults;
if (results.length > 0) {
const hitNode = results[0].collider.node;
console.log(`🎯 Попадание по объекту: ${hitNode.name}`);
// Подсвечиваем модель
this._highlightModel(hitNode);
// Перемещаем игрока к объекту
this._movePlayer(hitNode);
} else {
console.log('❌ Raycast ничего не нашел.');
}
} else {
console.log('⚠️ Raycast не сработал.');
}
}
private _highlightModel(model: Node) {
const highlighter = model.getComponent(PulsatingHighlighter);
if (highlighter) {
if (!EquipmentManager.instance) {
console.warn('🚨 EquipmentManager не доступен!');
return;
}
// Получаем список датчиков
const sensors = EquipmentManager.instance.dataList;
// Ищем датчик, соответствующий имени, указанному в PulsatingHighlighter (sensorName)
const sensorData = sensors.find((s) => s.name === highlighter.sensorName);
if (sensorData) {
let color = "";
if (sensorData.value === 2) {
color = "red";
} else if (sensorData.value === 1) {
color = "green";
} else if (sensorData.value === 0) {
color = "yellow";
} else {
console.warn(`Неожиданное значение sensorData.value: ${sensorData.value}`);
return;
}
highlighter.switchToColor(color);
} else {
console.warn(`Датчик с именем ${highlighter.sensorName} не найден.`);
}
}
}
private _movePlayer(model: Node) {
const meshRenderer = model.getComponent(MeshRenderer);
if (!meshRenderer) {
console.warn(`🚨 У объекта ${model.name} нет MeshRenderer!`);
return;
}
// Создаем AABB и обновляем границы модели
const aabb = new geometry.AABB();
meshRenderer.model?.updateWorldBound();
if (meshRenderer.model?.worldBounds) {
aabb.copy(meshRenderer.model.worldBounds);
} else {
console.warn(`⚠️ Не удалось получить worldBounds у ${model.name}`);
return;
}
// Центр модели
const center = aabb.center.clone();
// Размер модели (полный размер, полученный из halfExtents)
const size = aabb.halfExtents.clone().multiplyScalar(2);
const maxDim = Math.max(size.x, size.y, size.z);
// Если камера не задана, используем FOV по умолчанию (60°)
let fov = 60;
if (this.camera) {
fov = this.camera.fov;
}
// Переводим угол в радианы
const fovRad = fov * (Math.PI / 180);
// Вычисляем расстояние: +5 для смещения
const distance = maxDim / (2 * Math.tan(fovRad / 2)) + 5;
// Вычисляем направление движения: используем локальный forward игрока
const forward = new Vec3(0, 0, 1);
Vec3.transformQuat(forward, forward, this.node.rotation);
// Инвертируем вектор с помощью статического метода
Vec3.negate(forward, forward);
// Вычисляем смещение: создаем копию forward и умножаем на distance
const offset = forward.clone();
offset.multiplyScalar(distance);
// Новая позиция = центр модели + смещение
const newPosition = center.clone().add(offset);
console.log(`🎥 Перемещение игрока к ${model.name} в позицию: `, newPosition);
tween(this.node)
.to(1.0, { position: newPosition })
.call(() => {
// После перемещения ориентируем игрока лицом к центру модели
this.node.lookAt(center);
})
.start();
}
}