Cocos2d-js03_画九宫格及对节点进行封装

Cocos2d-js03_画九宫格及对节点进行封装

1、实现画出背景,代码:

//绘制背景
 var lc = cc.LayerColor.create(cc.color(175,175,75),630,630);
lc.setPosition(cc.p(5,300));
lc.setAnchorPoint(cc.p(0,0));
lc.setTag(111);
this.addChild(lc);

2、绘画九宫格,代码:

//绘画九宫格 for(var i = 0;i <= 10; i++){
 //横线  var node = cc.DrawNode.create();
 node.drawSegment(cc.p(0,i*63),cc.p(630,1,cc.color(1,255));
 lc.addChild(node);
 //竖线  var node1 = cc.DrawNode.create();
 node1.drawSegment(cc.p(i*63,0),cc.p(i*63,630),255));
 lc.addChild(node1);
}

3、添加SnakeGame.js类,根据传入的参数不同,添加不同的精灵,代码:

/** * Created by chaoge on 15/6/23. */ var SnakeGame = cc.Node.extend({
 _type:null,ctor:function(type){
 this._super();
 this._type = type;
 var sp = cc.Sprite.create();
 //1蛇头 2身体 3食物  switch (this._type){
 case 1:
 sp = cc.Sprite.create(res.snakeHead);
 break;
 case 2:
 sp = cc.Sprite.create(res.snakeBody);
 break;
 case 3:
 sp = cc.Sprite.create(res.snakeFood);
 break;
 default :break;
 }
 sp.setAnchorPoint(0,0);
 sp.setPosition(0,0);
 this.addChild(sp);
 }
});

SnakeGame.create = function(arg){
 var snakeGame = new SnakeGame(arg);
 return snakeGame;
};

4、在GameScene里面添加头和食物,代码:

//添加蛇头 this._head = new SnakeGame(1);
this._head.setScale(0.9);
this._head.now_row = Math.round(Math.random()*9);
this._head.now_col = Math.round(Math.random()*9);
this._head.setPosition(cc.p(this._head.now_col*63,this._head.now_row*63));
lc.addChild(this._head,3);

//添加食物 this._food = new SnakeGame(3);
this._food.setScale(0.9);
this._food.now_row = Math.round(Math.random()*9);
this._food.now_col = Math.round(Math.random()*9);
this._food.setPosition(cc.p(this._food.now_col*63,this._food.now_row*63));
lc.addChild(this._food,3);

5、实现移动,代码:

//蛇头移动 switch (dir){
 case SNAKE_DIR.UP:
 this._head.now_row = this._head.now_row + 1;
 break;
 case SNAKE_DIR.DOWN:
 this._head.now_row = this._head.now_row - 1;
 break;
 case SNAKE_DIR.LEFT:
 this._head.now_col = this._head.now_col - 1;
 break;
 case SNAKE_DIR.RIGHT:
 this._head.now_col = this._head.now_col + 1;
 break;
 default :break;
}
this._head.setPosition(cc.p(this._head.now_col*63,this._head.now_row*63));
 
视频地址:http://www.9miaoketang.com/course/37
课程讨论帖地址:http://www.9miao.com/thread-64587-1-1.html
源码地址:https://store.cocos.com/stuff/show/128289.html
QQ交流群:83459374
后期也会把该源码传在群里面去,欢迎大家加入讨论!

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...