nomadro/apps/minigame-cocos/assets/scripts/ui/VirtualJoystick.ts
Eric 58a845db32 Add WeChat minigame triple-engine scaffold with Godot Chiang Mai plaza SoT.
Unity and Cocos stay as parallel schemes; apps/minigame ships the Godot 4.7 WeChat pack for DevTools.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-06 20:17:14 +08:00

102 lines
2.6 KiB
TypeScript

import {
_decorator,
Component,
Node,
EventTouch,
UITransform,
input,
Input,
EventKeyboard,
KeyCode,
} from 'cc'
import { getBus } from '../core/EventBus'
import { stickVector } from '../vendor/nipple-math'
const { ccclass, property } = _decorator
/**
* Left-zone virtual stick — math from nipplejs (MIT).
* Emits player:move-input; E / Space / right-tap → interact:request.
*/
@ccclass('VirtualJoystick')
export class VirtualJoystick extends Component {
@property(Node)
stickKnob: Node | null = null
@property
maxRadius = 72
@property
threshold = 0.1
private _active = false
private _origin = { x: 0, y: 0 }
onEnable() {
this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this)
this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this)
this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this)
this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this)
input.on(Input.EventType.KEY_DOWN, this.onKey, this)
}
onDisable() {
this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this)
this.node.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this)
this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this)
this.node.off(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this)
input.off(Input.EventType.KEY_DOWN, this.onKey, this)
}
private onKey(e: EventKeyboard) {
if (e.keyCode === KeyCode.KEY_E || e.keyCode === KeyCode.SPACE) {
getBus().emit('interact:request')
}
}
/** Editor button Click */
onInteractClick() {
getBus().emit('interact:request')
}
private zoneWidth(): number {
return this.node.getComponent(UITransform)?.width ?? 750
}
private onTouchStart(e: EventTouch) {
const ui = e.getUILocation()
if (ui.x > this.zoneWidth() * 0.45) {
getBus().emit('interact:request')
return
}
this._active = true
this._origin = { x: ui.x, y: ui.y }
}
private onTouchMove(e: EventTouch) {
if (!this._active) return
const ui = e.getUILocation()
const v = stickVector(
this._origin,
{ x: ui.x, y: ui.y },
this.maxRadius,
this.threshold,
)
if (this.stickKnob) {
this.stickKnob.setPosition(
v.x * this.maxRadius,
v.y * this.maxRadius,
0,
)
}
// UI +y up → world forward as -z for stickVector y
getBus().emit('player:move-input', { x: v.x, z: -v.y })
}
private onTouchEnd() {
this._active = false
getBus().emit('player:move-input', { x: 0, z: 0 })
if (this.stickKnob) this.stickKnob.setPosition(0, 0, 0)
}
}