I have a sprite renderer which tells my game engine how to render a sprite. The update method in this class gets called about 120
times per second. Running through a sprite sheet at that speed is too fast.
In my sprite class I have a property called duration
, which tells the renderer how many seconds the sprite should play for. Once it has reached the last frame it should start over.
I am not exactly sure how to calculate this with an update
that runs 120
times a second, and a sprite sheet that should last for x
seconds till it starts over.
class SpriteRenderer extends Component {
// The current frame
public frame: number = 0;
// The sprite reference
public sprite: Sprite = null;
update() {
// Number of frames in the sprite sheet
let frames = this.sprite.frames;
if (frames > 0) {
// The time in seconds the sprite sheet should play
let duration = this.sprite.duration;
if (/* What should go here? */) {
this.frame++;
if (this.frame > frames - 1) {
this.frame = 0;
}
}
}
}
}
You could implement a time variable that controls the frame time. This variable is a float and once it gets large enough you can do the next frame and reset the variable.
I have never done any type script, but this may work. It will at least give you an idea of what i am talking about.
If the update runs 120 times every second that means that it runs every 60/120 seconds 0.5.
Now we can increment currentTime
by 0.5 and check if the currentTime
> sprite.duration
*60 I think. :)
Exampe:
class SpriteRenderer extends Component {
// The current frame
public frame: number = 0;
// The sprite reference
public sprite: Sprite = null;
public currentTime: number = 0.0; //This is the current time.
public updateTime: number = this.sprite.duration*60; //This is how long the update time is.
update() {
this.currentTime += 0.5; //Add to the current time.
// Number of frames in the sprite sheet
let frames = this.sprite.frames;
if (frames > 0) {
// The time in seconds the sprite sheet should play
let duration = this.sprite.duration;
if (this.currentTime > this.sprite.duration*60) { //Check if the current time is more than the wait time.
this.currentTime = 0.0; //Reset the wait time.
this.frame++;
if (this.frame > frames - 1) {
this.frame = 0;
}
}
}
}
}