CocosCreator中游戏摇杆的实现

在rpg游戏,包括很多其他游戏中,都要用到摇杆操控角色进行移动的效果,可以说是很多游戏的必须模块,今天我们就来实现这个模块


效果展示:

CocosCreator中游戏摇杆的实现_第1张图片

首先准备好摇杆的素材

CocosCreator中游戏摇杆的实现_第2张图片

摇杆代码:joystick.js

cc.Class({
    extends: cc.Component,
    properties: {
        stick: cc.Node,
        max_R: 90,
    },
    start() {
        this.dir = cc.v2(0, 0);
        this.stick.setPosition(cc.v2(0, 0));
        this.stick.on(cc.Node.EventType.TOUCH_START, function (e) {
            //开始触摸
        }.bind(this), this);
        this.stick.on(cc.Node.EventType.TOUCH_MOVE, function (e) {
            //移动
            var screen_pos = e.getLocation();
            var pos = this.node.convertToNodeSpaceAR(screen_pos);
            //最大边距
            var len = pos.mag();
            this.dir.x = pos.x / len;// x cos
            this.dir.y = pos.y / len;// y sin
            if (len > this.max_R) {
                pos.x = pos.x * this.max_R / len;
                pos.y = pos.y * this.max_R / len;
            }
            this.stick.setPosition(pos);
        }.bind(this), this);
        this.stick.on(cc.Node.EventType.TOUCH_END, function (e) {
            //结束
            this.dir = cc.v2(0, 0);
            this.stick.setPosition(cc.v2(0, 0));
        }.bind(this), this);
        this.stick.on(cc.Node.EventType.TOUCH_CANCEL, function (e) {
            //触摸弹起
            this.stick.setPosition(cc.v2(0, 0));
            this.dir = cc.v2(0, 0);
        }.bind(this), this);
    },
    update(dt) { },
});

角色代码:tank

var joystick = require("joystick");

cc.Class({
    extends: cc.Component,
    properties: {
        stick: {
            type: joystick,
            default: null,
        },
        speed: 2000,
    },
    start() {  },
    update(dt) {
        if (this.stick.dir.x === 0 && this.stick.dir.y === 0) {
            return;
        }
        this.vx = this.speed * this.stick.dir.x;
        this.vy = this.speed * this.stick.dir.y;
        var sx = this.vx * dt;
        var sy = this.vy * dt;
        var r = Math.atan2(this.stick.dir.y, this.stick.dir.x);
        var degree = r * 180 / Math.PI;

        this.node.x += sx;
        this.node.y += sy;

        degree = 360 - degree;
        degree = degree + 90;
        this.node.angle = -degree;
    },
});

脚本代码写完后记得将脚本挂载在节点上(joystick挂载在摇杆上,tank挂载在角色节点上,完成后就可以实现用摇杆控制角色移动啦),

你可能感兴趣的:(cocos,creator学习日记)