examples/platformer: Refactoring

This commit is contained in:
Hajime Hoshi 2017-10-29 00:06:50 +09:00
parent fb7bf03e15
commit 38293f13d5

View File

@ -18,6 +18,7 @@ package main
import ( import (
"fmt" "fmt"
"github.com/hajimehoshi/ebiten" "github.com/hajimehoshi/ebiten"
"github.com/hajimehoshi/ebiten/ebitenutil" "github.com/hajimehoshi/ebiten/ebitenutil"
) )
@ -36,63 +37,52 @@ var (
rightSprite *ebiten.Image rightSprite *ebiten.Image
idleSprite *ebiten.Image idleSprite *ebiten.Image
backgroundImage *ebiten.Image backgroundImage *ebiten.Image
err error
isFirstFrame bool = true charX = 50
charY = 380
backgroundOptions = &ebiten.DrawImageOptions{}
charSpriteOptions = &ebiten.DrawImageOptions{}
) )
func update(screen *ebiten.Image) error { func update(screen *ebiten.Image) error {
// Draws Background Image
screen.DrawImage(backgroundImage, backgroundOptions)
// Resets
charX := 0.0
charY := 0.0
if isFirstFrame == true {
charY += 380
charX += 50
isFirstFrame = false
}
// Controls // Controls
if ebiten.IsKeyPressed(ebiten.KeyA) { if ebiten.IsKeyPressed(ebiten.KeyA) {
// Selects preloaded sprite // Selects preloaded sprite
loadedSprite = leftSprite loadedSprite = leftSprite
// Moves character 3px right // Moves character 3px right
charX -= 3.0 charX -= 3
} else if ebiten.IsKeyPressed(ebiten.KeyD) { } else if ebiten.IsKeyPressed(ebiten.KeyD) {
// Selects preloaded sprite // Selects preloaded sprite
loadedSprite = rightSprite loadedSprite = rightSprite
// Moves character 3px left // Moves character 3px left
charX += +3.0 charX += 3
} else { } else {
loadedSprite = idleSprite loadedSprite = idleSprite
} }
// Change gopher's position if ebiten.IsRunningSlowly() {
charSpriteOptions.GeoM.Translate(charX, charY) return nil
}
// Draws Background Image
op := &ebiten.DrawImageOptions{}
op.GeoM.Scale(0.5, 0.5)
screen.DrawImage(backgroundImage, op)
// Draws selected sprite image
op = &ebiten.DrawImageOptions{}
op.GeoM.Scale(0.5, 0.5)
op.GeoM.Translate(float64(charX), float64(charY))
screen.DrawImage(loadedSprite, op)
// FPS counter // FPS counter
fps := fmt.Sprintf("FPS: %f", ebiten.CurrentFPS()) fps := fmt.Sprintf("FPS: %f", ebiten.CurrentFPS())
ebitenutil.DebugPrint(screen, fps) ebitenutil.DebugPrint(screen, fps)
// Draws selected sprite image
screen.DrawImage(loadedSprite, charSpriteOptions)
return nil return nil
} }
func main() { func main() {
// Settings for images
backgroundOptions.GeoM.Scale(0.5, 0.5)
backgroundOptions.GeoM.Translate(0, 0)
charSpriteOptions.GeoM.Scale(0.5, 0.5)
// Preload images // Preload images
var err error
rightSprite, _, err = ebitenutil.NewImageFromFile("_resources/images/platformer/right.png", ebiten.FilterNearest) rightSprite, _, err = ebitenutil.NewImageFromFile("_resources/images/platformer/right.png", ebiten.FilterNearest)
if err != nil { if err != nil {
panic(err) panic(err)