天天看點

cocos creator+TS制作簡單搖杆控制

你可能感興趣:

cocoscreator+TS音效管理類

cocosceator+TS資源管理類

Cocos Creator+TS改造日志系統

今天看了以為id為KUOKUO衆享的部落客的關于搖杆控制的文章,自己便忍不住自己實作了一下,不禁感歎,部落客的實作的确很簡單,在這裡跟大家分享下。大家也可以去部落客的部落格裡面去看,如果部落客覺得我這篇文章有侵權的部分,請私信我。

接下來步入正題。

首先是節點建立:

cocos creator+TS制作簡單搖杆控制

 節點的觸摸監聽是放在了JoyStick節點上面

start () {
        //節點監聽
        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);
    }
           

在腳本裡面添加幾個屬性,友善進行使用

@property({type:cc.Integer,tooltip:"搖杆活動半徑"})
    private maxR:number = 0;

    @property({type:cc.Node,tooltip:"搖杆背景節點"})
    private bg:cc.Node = null;

    @property({type:cc.Node,tooltip:"搖杆中心節點"})
    private circle:cc.Node = null;

    @property({type:cc.Component.EventHandler,tooltip:"移動搖杆回調"})
    private joyStickCallback:cc.Component.EventHandler = null;
           

搖杆活動半徑是用來進行範圍限制的

/**
     * 半徑限制,目前位置*(maxR/目前位置),超過最大半徑限制就會是maxR
     * @param pos 位置
     */
    clampPos(pos:any){
        let len = pos.mag();
        if (len > this.maxR) {
            let k = this.maxR / len;
            pos.x *= k;
            pos.y *= k;
        }
    }
           

觸摸事件的處理:擷取目前的位置并轉化成節點坐标,設定中心點的位置和角度。

/** 根據位置轉化角度 */
    covertToAngle (pos) {
        let r = Math.atan2(pos.y, pos.x);
        let d = cc.misc.radiansToDegrees(r);
        return d;
    }

    //事件觸摸
    onTouchMove(event){
        let pos = this.node.convertToNodeSpaceAR(event.getLocation());
        this.clampPos(pos);
        this.circle.setPosition(pos);
        let angle = this.covertToAngle(pos);
        this.joyStickCallback.emit([pos,angle]);
    }

    //觸摸結束
    onTouchEnd(event){
        this.circle.setPosition(0,0);
        this.joyStickCallback.emit([cc.v2(0,0)]);
    }
           

控制角色移動:

vector:any;

    onLoad () {
        this.vector = cc.v2(0, 0);
    }

    /** 被觸發回調 */
    playerMoving (vector, angle) {
        this.vector.x = vector.x;
        this.vector.y = vector.y;
        if (angle) {
            this.node.angle = angle;
        }
    }

    update (dt) {
        const speed = 0.02;
        this.node.x += this.vector.x * speed;
        this.node.y += this.vector.y * speed;
    }
           
cocos creator+TS制作簡單搖杆控制

效果圖

繼續閱讀