Modeling the State
Okay, now that there are slide classes set up, we need a way to keep track of them. After all, we can't call the draw method of every slide every frame. For one, we would only ever see the last slide, and all of those draw calls would certainly slow down your program.
What we need:
- An array containing all of our slides
- A variable that keeps track of which slide needs to be shown
- A way to to forward and back in the slideshow based on user inputs
With that in mind, lets outline the constructor and method of the Model class:
class Model
{
constructor(){
this.slides
this.state
}
setup(){}
getInput(){}
next(){}
back(){}
draw(){}
}
Constructor
So Model has to keep track of the slides, and which one to show. This means that the slides have to be passed in as an array, and the state needs to start on the first slide.
...
constructor(slides) //later, you'll pass an array into this argument
{
this.slides = slides //the array wil then be assigned to this.slides
this.state = 0 //the state will start at 0 to line up with the first index o
}
...
Setup
Since all of the slides in this.slides
need to run their setup loops. You could just use a regular for loop to go through all your slides:
setup()
{
for (let i = 0; i < slides.length; i++)
{
slides[i].setup()
}
}
But it might be a little more neat and compact if you use a for of
loop:
setup()
{
for (let slide of this.slides)
{
slide.setup()
}
}
Draw
Now that you have an array of slides, you can use the state of your model to determine which slide is drawn.
draw()
{
this.slides[this.state].draw()
}
Because this.state
is initially zero, the next behavior you'll need is
Back and Next
The methods that manipulate this.state
are pretty straightforward: increment or decrement the state, but don't go past the first or last slides.
next()
{
if(this.state < this.slides.length-1)
this.state++
}
back()
{
if(this.state > 0)
this.state--
}
getInput
Now that you have methods to change the state, now you need a function to call them based on key inputs.
getInput(input)
{
switch(keyCode){
case 37://left arrow
this.back()
break
case 39://right arrow
this.next()
break
case 32://space
this.next()
break
}
}