cocos creator从零开发虚拟摇杆(06)-跟随摇杆

摇杆共有 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并运行程序,跟随摇杆可以移动了。

修改摇杆类型

跟随摇杆跟固定摇杆的逻辑是一样的,只是最开始不显示,当触摸开始时才显示并确定位置。

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!