引擎知识点:
Action(动作)、cc.RotateBy(旋转)、cc.RepeatForever(动作循环) 用法:
var sprite = cc.Sprite.create("a.png");
var rotate = cc.RotateBy.create(1,90);参数1:动作时间参数2:旋转的角度
sprite.runAction(rotate);//sprite在1秒内旋转90度
sprite.runAction(cc.RepeatForever(rotate));//sprite不断的旋转
sprite.stopAllActions();//停止所有动作
复制代码
更多用法参考官方测试例 -------------------------------------------------------------------------------------------------------------- 一、描绘熊 1、在src目录中新建BearSprite.js,并把路径加入到cocos2d.js文件中的appFiles数组中 2、定义BearSprite
var BearSprite = cc.Sprite.extend({
/**
*构造函数
**/
ctor:function(){
this._super();
}
});
3、Sprite默认没有图片,我们需要赋予一个图片
var BearSprite = cc.Sprite.extend({
ctor:function(){
this._super();
this.initWithFile(s_bear_eyesopen);//赋予图片元素
}
});
4、把BearSprite添加到游戏场景中
//添加蘑菇
this.bear = new BearSprite();
this.bear.setPosition(cc.p(240,60))
this.gameLayer.addChild(this.bear.,g_GameZOder.ui);
代码如下图:

刷新浏览器效果如下:
 二、让熊旋转起来~ 1、BearSprite中定义一个beginRotate方法,用来开始旋转
beginRotate:function(){
var rotate = cc.RotateBy.create(2,360); //旋转角度,第1个参数:时间,第2个参数:在这个时间内旋转的角度
var rep1 = cc.RepeatForever.create(rotate); //循环旋转
this.runAction(rep1);//执行
},
2、BearSprite中定义一个方法stopRotate,用来停止旋转的
stopRotate:function(){
this.stopAllActions();
}
3、在GameScene中调用beginRotate()即可旋转起来 this.bear.beginRotate(); //开始旋转 刷新浏览器查看效果,熊旋转起来了。 三、让熊移动起来~ 1、在GameSence和Bear中添加update方法作为每帧的循环 定义GameSence中的update作为主控制
update: function (dt) {
//dt为每帧所消耗的时间,单位为秒
}
2、在GameSence中的onEnter加入schedule来启动主update,如下 this.schedule(this.update,0);//参数1:执行函数,参数2:调用间隔时间,0为每帧都调用
 3、Bear中的update更新自己 定义速度velocity等于cc.p(150,150);
 定义update更新Bear位置等状态
update: function (dt) {
//移动位置
this.setPosition(cc.pAdd(this.getPosition(),cc.pMult(this.velocity,dt)));
}
this.velocity为移动的速度 在GameSence中的update加入bear的update
update: function (dt) {
//dt为每帧所消耗的时间,单位为秒
this.bear.update(dt);
}
一般来说有不断位移的话,速度最好乘以dt,这样看起来会流畅 以上通过update的循环可以使熊移动起来 刷新浏览器查看效果,熊旋移动起来了。 四、边界碰撞检测 1、BearSprite中定义半径radius来检测碰撞,赋值为25
 2、BearSprite中定义方法checkHitEdge来做边界碰撞检测 代码如下:
//检查边界碰撞
checkHitEdge: function () {
var pos = this.getPosition();
var winSize = cc.Director.getInstance().getWinSize();
//熊碰到右边边界
if (pos.x > winSize.width - this.radius) {
//假如向右移动
this.velocity.x *= -1;//改变水平速度方向
}
//熊碰到左边边界
if (pos.x < this.radius) {
this.velocity.x *= -1;//改变水平速度方向
}
//熊碰到下面边界
if (pos.y <= this.radius) {
//减少1生命
this.curSence.reduceLives();
}
//熊碰到上边边界
if (pos.y >= winSize.height - this.radius) {
this.velocity.y *= -1;
}
},255);">3、把检测函数checkHitEdge加入到update中,每帧都做判断
 刷新浏览器查看效果,熊旋碰到边界能够反弹回来了 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|