预备工作:将gif转换成一个个帧的图片 使用在线工具Piskel将gif导出为png的zip包
原理 对象类在draw的时候,每隔几帧换一个图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 class GuaAnimation { constructor (game) { this .game = game this .frames = [] for (let i = 0 ; i < 3 ; i++) { let name = `player${i} ` let t = this .game.getImgFromName(name) this .frames.push(t) } this .texture = this .frames[0 ] this .frameIndex = 0 ; this .frameCount = 3 ; this .x = 50 this .y = 50 } static new (game) { return new this (game) } update() { this .frameCount-- if (this .frameCount <= 0 ) { this .frameCount = 3 this .frameIndex = (this .frameIndex + 1 ) % this .frames.length this .texture = this .frames[this .frameIndex] } } draw() { log(this .frameIndex) this .game.drawImage(this ) } }
如果有多种状态 frames数组需要改为animations对象,animations对象中存着不同状态下图片的数组
this.texture = this.animations[this.animationName][0]
或者采用一个函数(会重复使用的地方都可以用函数替换)
1 2 3 frames(){ return this .animations[this .animationName] }
实现翻转图片操作 心得
当一个变量生命周期很短的情况下,就用一个字母来做变量名
每三帧换一次图片,使用这种写法。注意触类旁通
1 2 3 4 5 6 7 8 9 10 11 12 this .frameIndex = 0 ; this .frameCount = 3 ;update() { this .frameCount-- if (this .frameCount <= 0 ) { this .frameCount = 3 this .frameIndex = (this .frameIndex + 1 ) % this .frames.length this .texture = this .frames[this .frameIndex] } }
拓展知识 在Javascript中使用模板字符串
简单版本
复杂版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 var createStrWithFormat = function (string ) { try { var args = arguments ; var pattern = new RegExp ("%([0-9]+)" , "g" ); return String (string).replace(pattern , function (match, index ) { if (index == 0 || index >= args.length) { throw "Invalid index in format string" ; } return args[index]; }); } catch (e) { log("createWithFormat error : " + e); return "" ; } } createStrWithFormat("this is a %1 speaking" , "male" )