CocosCreator之KUOKUO带你封装个摇杆

摘要

关于摇杆的实现网上有很多,但是耦合度比较高。今天 KUOKUO 将摇杆实现抽出来,单独一个脚本并声明了一个可拖入回调。

正文

版本说明

使用 CocosCreator 的 2.2.0 版本演示。

节点层级

新建个空节点作为管理节点(joystick),然后是背景与中心节点。

监听事件建议把监听写在背景节点,这样触摸范围大些,体验好。

// joyBk为背景节点
start () {
    this.joyBk.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
    this.joyBk.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
    this.joyBk.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
    this.joyBk.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
},
最大限制

获取到触摸位置后转化节点坐标下位置。

let pos = this.node.convertToNodeSpaceAR(e.getLocation());

然后,如果手指出圆了,要进行限位。假如最大半径 100,触摸位置为 150,那么就让 150 乘以 100/150;这样就转化回来了。

/** 根据半径限制位置 */
clampPos (pos) {
    let len = pos.mag();
    if (len > this.maxR) {
        let k = this.maxR / len;
        pos.x *= k;
        pos.y *= k;
    }
},

完整的处理代码:

let pos = this.node.convertToNodeSpaceAR(e.getLocation());
this.clampPos(pos);
this.midNode.setPosition(pos.x, pos.y);
回调数据

这样我们就算出了位置,接下来算角度。

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

好了,位置和角度都有了,摇杆的脚本任务完成了,那么如何做个回调呢?先声明一个变量,类型为 cc.Component.EventHandler。

properties: {
    /** 摇杆移动回调 */
    joyCallBack:  {
        default: [],
        type: cc.Component.EventHandler,
        displayName: '摇杆移动回调',
        tooltip: '触发touchmove后分发数据'
    }
},

然后将数据传出去:

onTouchMove (e) {
    let pos = this.node.convertToNodeSpaceAR(e.getLocation());
    this.clampPos(pos);
    this.midNode.setPosition(pos.x, pos.y);
    let angle = this.covertToAngle(pos);
    // 触发回调
    this.joyCallBack.emit([pos, angle]);
},


玩家脚本:

cc.Class({
    extends: cc.Component,

    properties: {
    },

    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;
    },
});

结语

这样就实现了摇杆脚本只处理摇杆数据,谁用谁传个回调进来。

2019!让我们一起学习!

O(∩_∩)O~~

源码在我的GitHub的MyComponent中

https://github.com/KuoKuo666;

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KUOKUO众享

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值