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

修改摇杆类型

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值