commit c909df6dd91353320591b79101cb0c7bc0af897b
parent c386d72caaf5e21a93e4d5be7d6397332a72b723
Author: bsandro <brian.drosan@gmail.com>
Date: Thu, 7 Oct 2021 01:52:56 +0300
Camera as a separate structure
Diffstat:
A | camera.go | | | 31 | +++++++++++++++++++++++++++++++ |
M | main.go | | | 22 | ++++++++++++---------- |
2 files changed, 43 insertions(+), 10 deletions(-)
diff --git a/camera.go b/camera.go
@@ -0,0 +1,31 @@
+package main
+
+import (
+ "math"
+)
+
+type Camera struct {
+ x, y float64
+ maxWidth, maxHeight float64
+}
+
+func (cam *Camera) Init(maxWidth, maxHeight float64) {
+ cam.maxWidth = maxWidth
+ cam.maxHeight = maxHeight
+}
+
+func (cam *Camera) ChangeX(diff float64) {
+ if diff < 0 {
+ cam.x = math.Max(cam.x+diff, 0)
+ } else {
+ cam.x = math.Min(cam.x+diff, cam.maxWidth)
+ }
+}
+
+func (cam *Camera) ChangeY(diff float64) {
+ if diff < 0 {
+ cam.y = math.Max(cam.y+diff, 0)
+ } else {
+ cam.y = math.Min(cam.y+diff, cam.maxHeight)
+ }
+}
diff --git a/main.go b/main.go
@@ -8,21 +8,21 @@ import (
"github.com/hajimehoshi/ebiten/v2/inpututil"
_ "image/png"
"log"
- "math"
"os"
)
const (
- screenW = 1024
- screenH = 768
+ screenW = 1280
+ screenH = 480
magnification = 2
+ cameraStep = 10
)
type Game struct {
Inited bool
Map *Gamemap
PressedKeys []ebiten.Key
- ScreenPos struct{ x, y float64 }
+ Cam Camera
}
func (g *Game) Init() error {
@@ -37,6 +37,8 @@ func (g *Game) Init() error {
return err
}
+ g.Cam.Init(g.Map.RealWidth-screenW/magnification, g.Map.RealHeight-screenH/magnification)
+
return nil
}
@@ -45,13 +47,13 @@ func (g *Game) Update() error {
for _, key := range g.PressedKeys {
switch key {
case ebiten.KeyArrowLeft:
- g.ScreenPos.x = math.Max(g.ScreenPos.x-10, 0)
+ g.Cam.ChangeX(-cameraStep)
case ebiten.KeyArrowRight:
- g.ScreenPos.x = math.Min(g.ScreenPos.x+10, g.Map.RealWidth-screenW/magnification)
+ g.Cam.ChangeX(cameraStep)
case ebiten.KeyArrowUp:
- g.ScreenPos.y = math.Max(g.ScreenPos.y-10, 0)
+ g.Cam.ChangeY(-cameraStep)
case ebiten.KeyArrowDown:
- g.ScreenPos.y = math.Min(g.ScreenPos.y+10, g.Map.RealHeight-screenH/magnification)
+ g.Cam.ChangeY(cameraStep)
case ebiten.KeyQ:
os.Exit(0)
default:
@@ -65,11 +67,11 @@ func (g *Game) Draw(screen *ebiten.Image) {
for _, layer := range g.Map.Layers {
for _, t := range layer.Tiles {
opts := *t.Options
- opts.GeoM.Translate(-g.ScreenPos.x, -g.ScreenPos.y)
+ opts.GeoM.Translate(-g.Cam.x, -g.Cam.y)
screen.DrawImage(t.Image, &opts)
}
}
- ebitenutil.DebugPrint(screen, fmt.Sprintf("TPS: %0.2f, screen: %v", ebiten.CurrentTPS(), g.ScreenPos))
+ ebitenutil.DebugPrint(screen, fmt.Sprintf("TPS: %0.2f, screen: %v", ebiten.CurrentTPS(), g.Cam))
}
func (g *Game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {