— так компоненты не упадут, даже если кнопка или её node к моменту onDestroy уже не существует сделал ноды менеджеров списка оборудовани, деталей, и аварий Persistent Node, чтобы при смене сцены не сбрасывалось их состояние.
65 lines
2.3 KiB
TypeScript
65 lines
2.3 KiB
TypeScript
// 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);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|