Clamp camera zoom and position

This commit is contained in:
Trevor Slocum 2022-11-09 17:08:54 -08:00
parent 6c76e9e5cc
commit 250b027164
3 changed files with 36 additions and 17 deletions

View File

@ -3,6 +3,7 @@ package game
import (
"image/color"
"log"
"math"
"os"
"code.rocketnine.space/tslocum/commandeuropa/component"
@ -44,6 +45,11 @@ func (g *Game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeigh
// Handle window resize.
if outsideWidth != world.ScreenWidth || outsideHeight != world.ScreenHeight {
world.ScreenWidth, world.ScreenHeight = outsideWidth, outsideHeight
mapSize := float64(16 * 128)
minZoomWidth := float64(world.ScreenWidth) / mapSize
minZoomHeight := float64(world.ScreenHeight) / mapSize
world.MinCamScale = int(math.Ceil(math.Max(minZoomWidth, minZoomHeight)))
}
return outsideWidth, outsideHeight

View File

@ -12,7 +12,20 @@ type HandleInput struct {
}
func (r *HandleInput) Update(e gohan.Entity) error {
const panDistance = 3
// Zoom with mouse.
_, scroll := ebiten.Wheel()
if scroll < 0 {
world.CamScale -= 1
} else if scroll > 0 {
world.CamScale += 1
}
// Clamp camera zoom.
if world.CamScale < world.MinCamScale {
world.CamScale = world.MinCamScale
}
panDistance := 4
// Pan with keyboard.
if ebiten.IsKeyPressed(ebiten.KeyLeft) {
@ -28,22 +41,6 @@ func (r *HandleInput) Update(e gohan.Entity) error {
world.CamY += panDistance
}
// Zoom with mouse.
const minZoom = 1
const maxZoom = 7
_, scroll := ebiten.Wheel()
if scroll < 0 {
world.CamScale -= 1
if world.CamScale < minZoom {
world.CamScale = minZoom
}
} else if scroll > 0 {
world.CamScale += 1
if world.CamScale > maxZoom {
world.CamScale = maxZoom
}
}
// Pan with mouse.
const panArea = 7
x, y := ebiten.CursorPosition()
@ -57,6 +54,20 @@ func (r *HandleInput) Update(e gohan.Entity) error {
} else if y >= world.ScreenHeight-panArea {
world.CamY += panDistance
}
// Clamp camera position.
halfWidth := (world.ScreenWidth / 2) / world.CamScale
halfHeight := (world.ScreenHeight / 2) / world.CamScale
if world.CamX < halfWidth {
world.CamX = halfWidth
} else if world.CamX > (16*128)-halfWidth {
world.CamX = (16 * 128) - halfWidth
}
if world.CamY < halfHeight {
world.CamY = halfHeight
} else if world.CamY > (16*128)-halfHeight {
world.CamY = (16 * 128) - halfHeight
}
return nil
}

View File

@ -17,6 +17,8 @@ var (
CamScale = 1
MinCamScale = 1
Map []MapTile
Debug int