ebiten/examples/blocks/blocks/scenemanager.go

95 lines
2.0 KiB
Go
Raw Normal View History

// Copyright 2014 Hajime Hoshi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2014-12-09 15:16:04 +01:00
2014-12-08 17:35:35 +01:00
package blocks
2013-12-18 10:05:28 +01:00
import (
2014-12-09 14:09:22 +01:00
"github.com/hajimehoshi/ebiten"
2013-12-18 10:05:28 +01:00
)
var (
transitionFrom *ebiten.Image
transitionTo *ebiten.Image
)
2013-12-18 19:21:25 +01:00
func init() {
2018-02-13 18:55:51 +01:00
transitionFrom, _ = ebiten.NewImage(ScreenWidth, ScreenHeight, ebiten.FilterDefault)
transitionTo, _ = ebiten.NewImage(ScreenWidth, ScreenHeight, ebiten.FilterDefault)
2013-12-18 10:05:28 +01:00
}
type Scene interface {
2014-12-29 05:36:29 +01:00
Update(state *GameState) error
Draw(screen *ebiten.Image)
2013-12-18 10:05:28 +01:00
}
2013-12-18 19:21:25 +01:00
const transitionMaxCount = 20
2013-12-18 10:05:28 +01:00
type SceneManager struct {
2013-12-18 19:21:25 +01:00
current Scene
next Scene
transitionCount int
2013-12-18 10:05:28 +01:00
}
2018-01-22 07:12:17 +01:00
type GameState struct {
SceneManager *SceneManager
Input *Input
2013-12-18 10:05:28 +01:00
}
2018-01-22 07:12:17 +01:00
func (s *SceneManager) Update(input *Input) error {
if s.transitionCount == 0 {
return s.current.Update(&GameState{
SceneManager: s,
Input: input,
})
2013-12-18 19:21:25 +01:00
}
2018-01-22 07:12:17 +01:00
s.transitionCount--
if s.transitionCount > 0 {
return nil
2013-12-18 10:05:28 +01:00
}
2018-01-22 07:12:17 +01:00
s.current = s.next
s.next = nil
2014-12-29 05:36:29 +01:00
return nil
2013-12-18 10:05:28 +01:00
}
func (s *SceneManager) Draw(r *ebiten.Image) {
2018-01-22 07:12:17 +01:00
if s.transitionCount == 0 {
s.current.Draw(r)
return
2014-12-29 05:36:29 +01:00
}
2018-01-22 07:12:17 +01:00
transitionFrom.Clear()
s.current.Draw(transitionFrom)
2013-12-18 19:21:25 +01:00
transitionTo.Clear()
s.next.Draw(transitionTo)
2013-12-18 19:21:25 +01:00
r.DrawImage(transitionFrom, nil)
2013-12-18 19:21:25 +01:00
2018-01-22 07:12:17 +01:00
alpha := 1 - float64(s.transitionCount)/float64(transitionMaxCount)
op := &ebiten.DrawImageOptions{}
op.ColorM.Scale(1, 1, 1, alpha)
r.DrawImage(transitionTo, op)
2013-12-18 10:05:28 +01:00
}
func (s *SceneManager) GoTo(scene Scene) {
2018-01-22 07:12:17 +01:00
if s.current == nil {
s.current = scene
} else {
s.next = scene
s.transitionCount = transitionMaxCount
}
2013-12-18 10:05:28 +01:00
}