43 lines
1.5 KiB
TypeScript
43 lines
1.5 KiB
TypeScript
// scripts/ui/ScrollHandler.ts
|
||
import { _decorator, Component, ScrollView, ScrollBar, UITransform, EventTouch, Vec3, clamp } from 'cc';
|
||
const { ccclass, property } = _decorator;
|
||
|
||
@ccclass('ScrollHandler')
|
||
export class ScrollHandler extends Component {
|
||
@property(ScrollView) scrollView: ScrollView = null!;
|
||
@property(ScrollBar) scrollBar: ScrollBar = null!;
|
||
|
||
onLoad() {
|
||
// Подпишемся, только если есть handle-спрайт
|
||
const handleSprite = this.scrollBar.handle;
|
||
if (!handleSprite) {
|
||
console.error('ScrollHandler: у ScrollBar нет handle–спрайта!');
|
||
return;
|
||
}
|
||
handleSprite.node.on('touch-move', this.onDrag, this);
|
||
}
|
||
|
||
onDestroy() {
|
||
// Безопасно отписываемся от события touch-move
|
||
this.scrollBar.handle?.node?.off('touch-move', this.onDrag, this);
|
||
}
|
||
|
||
private onDrag(evt: EventTouch) {
|
||
const handleSprite = this.scrollBar.handle;
|
||
if (!handleSprite) return;
|
||
|
||
const barNode = this.scrollBar.node;
|
||
const ui = barNode.getComponent(UITransform)!;
|
||
const worldPos = evt.getLocation();
|
||
const local = ui.convertToNodeSpaceAR(new Vec3(worldPos.x, worldPos.y, 0));
|
||
|
||
const H = ui.height;
|
||
const handleH = handleSprite.node.getComponent(UITransform)!.height;
|
||
let pct = (local.y + H/2 - handleH/2) / (H - handleH);
|
||
pct = clamp(pct, 0, 1);
|
||
|
||
// ПРОПУСКАЕМ инверсию — передаём pct напрямую
|
||
this.scrollView.scrollToPercentVertical(pct, 0);
|
||
}
|
||
}
|