精靈類是任何一款遊戲引擎的核心,你所見到的圖檔畫面基本都是由它展現出來的,比如我們的遊戲背景,主角等等,是以學好Sprite精靈類對遊戲的畫面體驗有着很重要的影響。我們就先介紹他的建立方式,一般來說有以下5種:
第一種:
cc.Sprite.create(fileName)通過一張圖檔生成精靈對象
參數:圖檔的名稱。
var sprite1 = cc.Sprite.create("test.png"); //這裡圖檔名稱最好寫在resource.js裡面
sprite1.setPosition(cc.p(10,10));
this.addChild(sprite1);
第二種:
cc.Sprite.create(fileName, rect) 通過一張圖檔進行給定矩形裁剪生成精靈對象
參數1:圖檔名稱
參數2:矩形的區域
var sprite2 = cc.Sprite.create("test.png", cc.rect(0, 0, 50, 50));
sprite2.setPosition(cc.p(10,10));
this.addChild(sprite2);
第三種:
cc.Sprite.createWithSpriteFrame(spriteFrame)通過緩存中的幀生成精靈對象
參數:幀的名稱
var spriteFrameCache = cc.SpriteFrameCache.getInstance(); //使用精靈幀緩存,友善後面多次使用
var frameCache = spriteFrameCache.addSpriteFrames(s_plist, s_png); //第一個參數plist檔案,第二個參數plist對應的png圖檔
var sprite3 = cc.Sprite.createWithSpriteFrame(spriteFrameCache.getSpriteFrame("test.png"));//plist裡面對于的圖檔名稱
sprite1.setPosition(cc.p(10,10));
this.addChild(sprite3);
第四種:
cc.Sprite.createWithSpriteFrameName(spriteFrameName)另外一種通過緩存中的幀生成精靈對象
參數:幀的名稱
var sprite4 = cc.Sprite.createWithSpriteFrameName("test1.png");
sprite4.setPosition(cc.p(10,10));
this.addChild(sprite4);
第五種:
cc.Sprite.createWithTexture(texture, rect) 通過Texture2D,并進行裁剪生成精靈對象
參數1:Texture圖檔
參數2:矩形的區域
var batch = cc.SpriteBatchNode.create(s_mybach);
this.addChild(batch);
var sprite5 = cc.Sprite.createWithTexture(batch.getTexture(), cc.rect(0, 121, 85, 121)); //需要顯示的區域
var sprite6 = cc.Sprite.createWithTexture(batch.getTexture(), cc.rect(85, 121, 85, 121));
sprite5.setPosition(cc.p(10,10));
this.addChild(sprite5);
精靈類也有很多自己的屬性,比如設定旋轉角度,設定縮放,設定透明度等等,這些可以在官方的api中檢視到,我就列舉幾個我比較常用的方法。
setRotation(rotation)設定旋轉角度
setScale(scale)設定縮放值
setVisible(visible)設定是否可見
setOpacity(var)設定透明度
還有一些父類在精靈中常用的
setTag(var)設定标記
setAnchorPoint(point)設定錨點
getBoundingBox() 擷取rect大小
想自己建立一個屬于自己的Sprite也很簡單
var MySprite = cc.Sprite.extend({ //繼承cc.Sprite
ctor: function (fileName) {
this._super();
this.initWithFile(fileName); //初始化圖檔
},
xxx:function(){ //自己定義自己想要的方法
}
});
以上就是精靈類的介紹了,吃飯去咯~