精华
用Image+tween实现图片播放
总有人不务正业,不拿Phaser做游戏。 下面做个简单的类实现图片播放效果,可调速度; 运用Tween还可以实现各种播放效果,如倒序播放、来回、yoyo…
// SlideImage -- 图片播放类
// 注意:需要预先准备好图片数据,并且在preload里面加载到cache
var SlideImage = function(game, x, y, data){
Phaser.Image.call(this, game, x, y);
this.data = data || [];
this.idx = 0;
this._idx = 0;
this.speed = 10; // 默认播放速度,10帧/秒
this.tween = null;
if(this.data.length>0){
this.loadTexture(this.data[0].id); // 默认加载第一帧
this.tween = this.game.add.tween(this).to({_idx : this.data.length}, 1000 * this.data.length / this.speed , "Linear", false, 0, -1);
}
// 添加更新函数
this.update = function(){
var idx = Math.floor(this._idx) % this.data.length;
if(this.idx != idx){
this.idx = idx;
if(this.data.length>0){
this.loadTexture(this.data[idx].id);
}
}
};
// 添加一些其他函数
this.play = function(){
this.tween.start();
};
this.stop = function(){
this.tween.stop();
};
this.pause = function(){
this.tween.pause();
};
this.resume = function(){
this.tween.resume();
};
};
SlideImage.prototype = Object.create(Phaser.Image.prototype);
SlideImage.prototype.constructor = SlideImage;
3 回复
使用例子:
var GameState = function(game){
// 准备的图片数据:
var imgData = [
{id:"img001",src:"img/img001.png"},
{id:"img002",src:"img/img002.png"},
{id:"img003",src:"img/img003.png"},
{id:"img004",src:"img/img004.png"},
{id:"img005",src:"img/img005.png"}
];
this.preload = function(){
// 预先加载图片
for (var i = 0; i<imgData.length; i++){
this.game.load.image(imgData[i].id, imgData[i].src);
}
};
this.create = function(){
// 创建一个图片播放器,然后执行play()播放
var player = game.world.add(new SlideImage(game,0,0,imgData));
player.play();
};
};
棒!