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

前端之家收集整理的这篇文章主要介绍了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
后期也会把该源码传在群里面去,欢迎大家加入讨论!
原文链接:https://www.f2er.com/cocos2dx/342490.html

猜你在找的Cocos2d-x相关文章