yantar/assets/Scripts/ux/SceneLoaderOnDoubleClick.ts
Georgy Shive 98e9d62db7 везде где только мог сделал с безопасной подпиской/отпиской через optional chaining
— так компоненты не упадут, даже если кнопка или её node к моменту onDestroy уже не существует
сделал ноды менеджеров списка оборудовани, деталей,
и аварий Persistent Node, чтобы при смене сцены не сбрасывалось
их состояние.
2025-05-11 13:33:08 +07:00

65 lines
2.3 KiB
TypeScript
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.

// scripts/SceneLoaderOnDoubleClick3D.ts
import { _decorator, Component, director, SceneAsset, input, Input, EventMouse, geometry, PhysicsSystem, Camera } from 'cc';
import { SceneHistory } from '../utils/SceneHistory';
const { ccclass, property } = _decorator;
@ccclass('SceneLoaderOnDoubleClick3D')
export class SceneLoaderOnDoubleClick3D extends Component {
@property({ type: SceneAsset, tooltip: 'Сцена для загрузки при двойном клике' })
public targetScene: SceneAsset | null = null;
@property({ type: Camera, tooltip: 'Основная камера' })
public camera: Camera | null = null;
private _doubleClickThreshold = 300;
private _lastClickTime = 0;
onLoad() {
input.on(Input.EventType.MOUSE_DOWN, this.onMouseDown, this);
}
onDestroy() {
input?.off(Input.EventType.MOUSE_DOWN, this.onMouseDown, this);
}
private onMouseDown(event: EventMouse) {
if (event.getButton() !== EventMouse.BUTTON_LEFT) return;
const now = performance.now();
if (now - this._lastClickTime < this._doubleClickThreshold) {
this.handleDoubleClick(event);
this._lastClickTime = 0;
} else {
this._lastClickTime = now;
}
}
private handleDoubleClick(event: EventMouse) {
if (!this.camera) {
console.error('Камера не назначена!');
return;
}
const x = event.getLocationX();
const y = event.getLocationY();
const ray = new geometry.Ray();
this.camera.screenPointToRay(x, y, ray);
if (PhysicsSystem.instance.raycastClosest(ray)) {
const res = PhysicsSystem.instance.raycastClosestResult;
if (res.collider?.node === this.node) {
if (this.targetScene) {
// вариант с проверкой
const cur = director.getScene();
if (cur) {
SceneHistory.lastScene = cur.name;
} else {
console.warn('Не удалось получить текущую сцену');
}
director.loadScene(this.targetScene.name);
}
}
}
}
}