新建scripts/JoyStick.ts
,内容如下,把它挂载到JoyStick
节点上。
const { ccclass, property } = cc._decorator
@ccclass
export default class JoyStick extends cc.Component {
private ringNode: cc.Node
private dotNode: cc.Node
private _canMove = false
protected onLoad(): void {
this.ringNode = this.node.getChildByName('ring')
this.dotNode = this.ringNode.getChildByName('dot')
this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this)
this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this)
this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this)
this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this)
}
private onTouchStart(event: cc.Event.EventTouch) {
this._canMove = true
const pos = this.node.convertToNodeSpaceAR(event.getLocation())
const ringPos = this.ringNode.getPosition()
const len = pos.sub(ringPos).len()
if (len > this.ringNode.width / 2) {
this._canMove = false
return
}
this.dotNode.setPosition(this.ringNode.convertToNodeSpaceAR(event.getLocation()))
}
private onTouchMove(event: cc.Event.EventTouch) {
if (!this._canMove) return
const posDelta = event.getDelta()
this.dotNode.setPosition(this.dotNode.getPosition().add(posDelta))
const len = this.dotNode.position.len()
const maxLen = this.ringNode.width / 2
const ratio = len / maxLen
if (ratio > 1) {
this.dotNode.setPosition(this.dotNode.position.div(ratio))
}
}
private onTouchEnd() {
if (!this._canMove) return
this.dotNode.setPosition(cc.Vec2.ZERO)
}
}
触摸开始时,判断触摸点是否在
ring
圆内,是就把dot
节点位置设置在触摸点,不是就不做任何操作并不响应后续的事件。触摸移动时,设置
dot
节点的位置,如果位置超过最大范围则重新设置在最大范围处。触摸结束时,
dot
位置重新归零。
运行程序,虚拟摇杆可以移动了。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。