摇杆共有 3 种类型,即固定、跟随、跟随并移动,之前已经做了固定摇杆类型,这里做跟随摇杆类型。
编辑scripts/JoyStick.ts
,添加JoystickType
枚举。
const { ccclass, property } = cc._decorator
export enum JoystickType {
Fixed,
Follow,
FollowMove,
}
添加joystickType
属性。
@property({ type: cc.Enum(JoystickType) })
private joystickType: JoystickType = JoystickType.Fixed
@property([cc.Component.EventHandler])
private handlers: cc.Component.EventHandler[] = []
修改onLoad
方法,当不是Fixed
类型时隐藏摇杆。
this.dotNode = this.ringNode.getChildByName('dot')
if (this.joystickType != JoystickType.Fixed) {
this.ringNode.opacity = 0
}
this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this)
修改onTouchStart
方法,当不是Fixed
类型时显示摇杆。
private onTouchStart(event: cc.Event.EventTouch) {
this._canMove = true
const pos = this.node.convertToNodeSpaceAR(event.getLocation())
if (this.joystickType == JoystickType.Fixed) {
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()))
} else {
this.ringNode.opacity = 255
this.ringNode.setPosition(pos)
}
}
修改onTouchEnd
方法,当不是Fixed
类型时隐藏摇杆。
private onTouchEnd() {
if (!this._canMove) return
if (this.joystickType != JoystickType.Fixed) {
this.ringNode.opacity = 0
}
this.dotNode.setPosition(cc.Vec2.ZERO)
this.handlers.forEach(handler => handler.emit([cc.Vec2.ZERO]))
this.node.emit('JoyStick', cc.Vec2.ZERO)
}
场景修改JoyStick
节点joystickType
值为Follow
并运行程序,跟随摇杆可以移动了。
跟随摇杆跟固定摇杆的逻辑是一样的,只是最开始不显示,当触摸开始时才显示并确定位置。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。