1 /** 2 Displays an animated Game Object 3 @author <a href="mailto:matthewcasperson@gmail.com">Matthew Casperson</a> 4 @class 5 */ 6 function AnimatedGameObject() 7 { 8 /** 9 Defines the current frame that is to be rendered 10 @type Number 11 */ 12 this.currentFrame = 0; 13 /** 14 Defines the frames per second of the animation 15 @type Number 16 */ 17 this.timeBetweenFrames = 0; 18 /** 19 The number of individual frames held in the image 20 @type Number 21 */ 22 /** 23 Time until the next frame 24 @type number 25 */ 26 this.timeSinceLastFrame = 0; 27 /** 28 The width of each individual frame 29 @type Number 30 */ 31 this.frameWidth = 0; 32 33 /** 34 Initialises this object 35 @param image The image to be displayed 36 @param x The position on the X axis 37 @param y The position on the Y axis 38 @param z The depth 39 @param frameCount The number of animation frames in the image 40 @param fps The frames per second to animate this object at 41 */ 42 this.startupAnimatedGameObject = function(/**Image*/ image, /**Number*/ x, /**Number*/ y, /**Number*/ z, /**Number*/ frameCount, /**Number*/ fps) 43 { 44 if (frameCount <= 0) throw "framecount can not be <= 0"; 45 if (fps <= 0) throw "fps can not be <= 0" 46 47 this.startupVisualGameObject(image, x, y, z); 48 this.currentFrame = 0; 49 this.frameCount = frameCount; 50 this.timeBetweenFrames = 1/fps; 51 this.timeSinceLastFrame = this.timeBetweenFrames; 52 this.frameWidth = this.image.width / this.frameCount; 53 54 return this; 55 } 56 57 this.setAnimation = function(/**Image*/ image, /**Number*/ frameCount, /**Number*/ fps) 58 { 59 if (frameCount <= 0) throw "framecount can not be <= 0"; 60 if (fps <= 0) throw "fps can not be <= 0" 61 62 this.image = image; 63 this.currentFrame = 0; 64 this.frameCount = frameCount; 65 this.timeBetweenFrames = 1/fps; 66 this.timeSinceLastFrame = this.timeBetweenFrames; 67 this.frameWidth = this.image.width / this.frameCount; 68 } 69 70 /** 71 Draws this element to the back buffer 72 @param dt Time in seconds since the last frame 73 @param context The context to draw to 74 @param xScroll The global scrolling value of the x axis 75 @param yScroll The global scrolling value of the y axis 76 */ 77 this.draw = function(/**Number*/ dt, /**CanvasRenderingContext2D*/ context, /**Number*/ xScroll, /**Number*/ yScroll) 78 { 79 var sourceX = this.frameWidth * this.currentFrame; 80 context.drawImage(this.image, sourceX, 0, this.frameWidth, this.image.height, this.x - xScroll, this.y - yScroll, this.frameWidth, this.image.height); 81 82 this.timeSinceLastFrame -= dt; 83 if (this.timeSinceLastFrame <= 0) 84 { 85 this.timeSinceLastFrame = this.timeBetweenFrames; 86 ++this.currentFrame; 87 this.currentFrame %= this.frameCount; 88 } 89 } 90 } 91 92 AnimatedGameObject.prototype = new VisualGameObject;