cocos creator 摇杆(单触点)

cc.Class({
    extends: cc.Component,
    properties: {
    },
    onLoad () {
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchDown, 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);
    },
    start () {
        this._drag = this.node.getChildByName('Drag');
        this._bg = this.node.getChildByName('Background');
        this._dragR = this._drag.height / 2; //设定最大拖动半径
        this._rockerV2 = cc.v2(0, 0); 
        this._bg.opacity = 0; //背景初始透明度
        this._drag.opacity = 200;  //摇杆初始透明度
    },
    onDestroy () {
        this.node.off(cc.Node.EventType.TOUCH_START, this.onTouchDown, this);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.off(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    },
    onTouchDown(event){ //按下摇杆
        if(event.getID()==0){
            this.onTouchMove(event)
            //点击动画
            cc.tween(this._bg).to(0.6, {opacity: 150}).start(); 
            cc.tween(this._drag).to(0.6, {opacity: 240}).start();
        }
    },
    onTouchMove(event){ //移动摇杆
        if(event.getID()==0){
            let v2 = this.node.convertToNodeSpaceAR(event.getLocation());
            this._rockerV2 = v2.normalize();
            if(v2.mag() > this._dragR) //检测是否超出拖动半径
                v2 = this._rockerV2.multiplyScalar(this._dragR);
            this._drag.setPosition(v2);
        }
    },
    onTouchEnd(event){ //抬起摇杆
        if(event.getID()==0){
            this._rockerV2 = cc.v2(0, 0);
            this._drag.setPosition(this._rockerV2);
            cc.tween(this._bg).to(0.6, {opacity: 0}).start();
            cc.tween(this._drag).to(0.6, {opacity: 200}).start();
        }
    },
    get(){ //获取摇杆坐标
        let pos = this._drag.getPosition();
        if(pos.mag() == 0)
            return cc.v2(0, 0);
        return pos.normalize()  //归一化, 只要移动速度固定
        //return pos.divide(this._dragR)  // 摇杆不到边缘速度会递减
    },
});

 

  3个sprite  父物体绑定脚本

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值