Cocos Creator 案例源码分享一(平面魔方)

博主分享了使用CocosCreator和JavaScript初学游戏编程的过程,创建了一个5x5彩色魔方游戏。游戏源码已公开,包括设置游戏网格、动态调整难度、初始化方块颜色等方面。文章详细解释了关键代码,如设置游戏尺寸、绘制方块等,适合CocosCreator新手参考学习。
摘要由CSDN通过智能技术生成

最近闲来无聊,想学习Cocos Creator游戏编程,并把自己在学习过程中的一些案例分享出来,后面会陆续推出一些小游戏的,由于本人第一次接触Cocos Creator 和JavaScript,代码多有疏漏欢迎留言指正。

游戏画面展示:

     

游戏源码共享:

https://download.csdn.net/download/hucailai/20016067

游戏引擎版本:2.3.3

游戏加载:

        onLoad: function () {

            this.cellCnt = 5;

            this.cellWidth = 100
            this.cellHeight = this.cellWidth
            this.interval = 20

            this.maskNode.width = this.cellCnt * this.cellWidth + (this.cellCnt - 1) * this.interval;
            this.maskNode.height = this.cellCnt * this.cellHeight + (this.cellCnt - 1) * this.interval;

            this.baseX = 0 - (this.maskNode.width)/2 + this.cellWidth / 2
            this.baseY =  0 - (this.maskNode.height)/2 + this.cellHeight / 2

            this.movingCellArray = new Array;

        },

为了能动态调整游戏的难度可以通过修改cellCnt,默认是5*5的格子,cellWidth、cellHeight分别表示格子的宽和高,interval表示格子的之间的间隔,maskNode是遮盖的Node,超出这个Node范围的区域会被遮盖。baseX,baseY表示最最左下方的方格的left和bottom的坐标,是整个魔方的基准坐标,通过上面的这些参数可以确定所有魔方格子的位置。movingCellArray是鼠标移动魔方时管理的移动的格子。

开始游戏:

    start: function () {

        var colors = [[255,0,0],[0,255,0],[0,0,255],[255,255,0],[255,0,255],[0,255,255],[227,221,3]]
        this.cellArray = new Array();
        for (i = 0; i < this.cellCnt; i++){
            this.cellArray[i]=new Array();
            for (j = 0; j < this.cellCnt; j++){
                x = this.baseX + j*(this.cellWidth+this.interval)
                y = this.baseY + i*(this.cellHeight+this.interval)
                this.cellArray[i][j] = this.addCell(x, y, this.cellWidth, this.cellHeight, colors[i][0], colors[i][1], colors[i][2])
            }
        }
      },

colors是预置的方块颜色,调大cellCnt大小时,预置方块颜色需要添加,不然会越界。最终是调用addCell,绘制每个方块。所有方块的Node都保存在cellArray中,其他代码不用过多解释

添加方格:

    addCell: function(x,y,width, Height, R, G, B){
        cc.log("addCell")
        var node = new cc.Node('Sprite');
        var sp = node.addComponent(cc.Sprite);
        var spriteFrame = new cc.SpriteFrame();
        var texture = new cc.Texture2D();
        node.setPosition(x, y);

        texture.initWithData(new Uint8Array([R, G, B]), cc.Texture2D.PixelFormat.RGB888, 1, 1, cc.winSize);
        spriteFrame.setTexture(texture);
        spriteFrame.setRect(cc.rect(0, 0, width, Height));
        sp.spriteFrame = spriteFrame;
        node.parent = this.rootCell;

        return node
    },

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

hucailai

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

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

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

打赏作者

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

抵扣说明:

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

余额充值