2022-12-09 15:48:29 +08:00
|
|
|
import { _decorator, Component, Node, input, Input, EventTouch, Vec2, Vec3, UITransform } from "cc"
|
|
|
|
const { ccclass, property } = _decorator
|
2022-11-27 23:23:47 +08:00
|
|
|
|
2022-12-08 21:14:02 +08:00
|
|
|
@ccclass("JoyStickManager")
|
2022-11-27 23:23:47 +08:00
|
|
|
export class JoyStickManager extends Component {
|
2022-12-09 15:48:29 +08:00
|
|
|
input: Vec2 = Vec2.ZERO
|
2022-12-08 21:14:02 +08:00
|
|
|
|
2022-12-09 15:48:29 +08:00
|
|
|
private body: Node
|
|
|
|
private stick: Node
|
|
|
|
private defaultPos: Vec2
|
|
|
|
private radius: number = 0
|
2022-12-08 21:14:02 +08:00
|
|
|
|
|
|
|
init() {
|
2022-12-09 15:48:29 +08:00
|
|
|
this.body = this.node.getChildByName("Body")
|
|
|
|
this.stick = this.body.getChildByName("Stick")
|
|
|
|
const { x, y } = this.body.position
|
|
|
|
this.defaultPos = new Vec2(x, y)
|
|
|
|
this.radius = this.body.getComponent(UITransform).contentSize.x / 2
|
|
|
|
|
|
|
|
input.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
|
|
|
|
input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
|
|
|
|
input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
|
2022-12-08 21:14:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
onDestroy() {
|
2022-12-09 15:48:29 +08:00
|
|
|
input.off(Input.EventType.TOUCH_START, this.onTouchStart, this)
|
|
|
|
input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
|
|
|
|
input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this)
|
2022-12-08 21:14:02 +08:00
|
|
|
}
|
|
|
|
|
2022-12-09 15:48:29 +08:00
|
|
|
onTouchStart(e: EventTouch) {
|
|
|
|
const touchPos = e.getUILocation()
|
|
|
|
this.body.setPosition(touchPos.x, touchPos.y)
|
|
|
|
}
|
2022-11-27 23:23:47 +08:00
|
|
|
|
2022-12-09 15:48:29 +08:00
|
|
|
onTouchMove(e: EventTouch) {
|
|
|
|
const touchPos = e.getUILocation()
|
|
|
|
const stickPos = new Vec2(touchPos.x - this.body.position.x, touchPos.y - this.body.position.y)
|
|
|
|
if (stickPos.length() > this.radius) {
|
|
|
|
stickPos.multiplyScalar(this.radius / stickPos.length())
|
2022-11-27 23:23:47 +08:00
|
|
|
}
|
2022-12-09 15:48:29 +08:00
|
|
|
this.stick.setPosition(stickPos.x, stickPos.y)
|
2022-11-27 23:23:47 +08:00
|
|
|
|
2022-12-09 15:48:29 +08:00
|
|
|
this.input = stickPos.clone().normalize()
|
|
|
|
console.log(this.input)
|
2022-12-08 21:14:02 +08:00
|
|
|
}
|
2022-11-27 23:23:47 +08:00
|
|
|
|
2022-12-08 21:14:02 +08:00
|
|
|
onTouchEnd() {
|
2022-12-09 15:48:29 +08:00
|
|
|
this.body.setPosition(this.defaultPos.x, this.defaultPos.y)
|
|
|
|
this.stick.setPosition(0, 0)
|
|
|
|
this.input = Vec2.ZERO
|
2022-12-08 21:14:02 +08:00
|
|
|
}
|
2022-11-27 23:23:47 +08:00
|
|
|
}
|