cocos creator从零开发虚拟摇杆(03)-固定摇杆

新建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位置重新归零。

运行程序,虚拟摇杆可以移动了。

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

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