Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var AnimMode =
- {
- FORWARD: 1,
- BACKWARD: -1,
- PINGPONG: 0
- };
- function Anim(img)
- {
- // Public stuff. Customise for each instance.
- this.spr = new Sprite(img);
- this.frame =
- {
- // Size of a frame as a factor of the whole image.
- size: createVector(1, 1),
- // You'll have to specify frame count automatically,
- // since the whole image might not be used if there
- // are multiple rows and columns.
- count: 1,
- // Probably do not touch this.
- curr: 0,
- // Probably do not touch this.
- prev: 0,
- // If you want to reuse the same frame multiple times,
- // set this to an array, like [0, 1, 0, 2] for example.
- order: null
- };
- this.speed = 1;
- this.playing = true;
- this.repeat = true;
- this.mode = AnimMode.FORWARD;
- // Internal variables. Don't touch.
- this.timer = 0;
- this.backward = false;
- this.draw = function(dt)
- {
- // Frames per column and row.
- var countPer = createVector
- (
- Math.round(1.0 / this.frame.size.x),
- Math.round(1.0 / this.frame.size.y)
- );
- // Actual count.
- var count;
- if (this.frame.order === null)
- count = Math.min(countPer.x * countPer.y, this.frame.count);
- else
- count = this.frame.order.length;
- // Tick away.
- if (this.playing)
- this.timer += dt;
- var time = this.timer * this.speed;
- this.frame.prev = this.frame.curr;
- // Current frame index.
- var f = Math.floor(Math.max(0, Math.floor(time % count)));
- if (this.mode == AnimMode.BACKWARD || this.backward)
- f = count - 1 - f;
- if (this.frame.order !== null)
- f = this.frame.order[f];
- this.frame.curr = f;
- // Check if the end has been reached in case of pingpong.
- if (this.mode == AnimMode.PINGPONG && f != this.frame.prev &&
- ((this.backward && this.frame.prev == 0) || (!this.backward && this.frame.prev == (count - 1))))
- {
- // Go to the new desired frame.
- f = this.frame.curr = (this.backward) ? 1 : (count - 2);
- // Update this so that the above check does not hold true again.
- this.frame.prev = (this.backward) ? (count - 1) : 0;
- // Reverse.
- this.backward = !this.backward;
- // Reset timer to match up with the new frame.
- this.timer = (count - 2) / this.speed;
- }
- // Index to position.
- this.spr.clp.pos = createVector
- (
- (f % countPer.x) / countPer.x,
- Math.floor(f / countPer.x) / countPer.y
- );
- this.spr.clp.size = this.frame.size;
- this.spr.draw();
- }
- this.reset = function()
- {
- this.frame.curr = this.frame.prev = 0;
- this.timer = 0;
- this.backward = false;
- };
- }
Add Comment
Please, Sign In to add comment