commandeuropa/system/handleinput.go

116 lines
2.9 KiB
Go

package system
import (
"code.rocketnine.space/tslocum/commandeuropa/component"
"code.rocketnine.space/tslocum/commandeuropa/world"
"code.rocketnine.space/tslocum/gohan"
"github.com/beefsack/go-astar"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/inpututil"
)
type HandleInput struct {
Once *component.Once
}
func (r *HandleInput) Update(e gohan.Entity) error {
// Update cursor position.
cx, cy := ebiten.CursorPosition()
world.CursorX, world.CursorY = float64(cx), float64(cy)
// Clamp cursor position.
if world.CursorX < 0 {
world.CursorX = 0
} else if world.CursorX > world.ScreenWidth-1 {
world.CursorX = world.ScreenWidth - 1
}
if world.CursorY < 0 {
world.CursorY = 0
} else if world.CursorY > world.ScreenHeight-1 {
world.CursorY = world.ScreenHeight - 1
}
// 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 := float64(4)
// Pan with keyboard.
if ebiten.IsKeyPressed(ebiten.KeyLeft) {
world.CamX -= panDistance
}
if ebiten.IsKeyPressed(ebiten.KeyRight) {
world.CamX += panDistance
}
if ebiten.IsKeyPressed(ebiten.KeyUp) {
world.CamY -= panDistance
}
if ebiten.IsKeyPressed(ebiten.KeyDown) {
world.CamY += panDistance
}
// Pan with mouse.
const panArea = 7
if world.CursorX <= panArea {
world.CamX -= panDistance
} else if world.CursorX >= world.ScreenWidth-panArea {
world.CamX += panDistance
}
if world.CursorY <= panArea {
world.CamY -= panDistance
} else if world.CursorY >= world.ScreenHeight-panArea {
world.CamY += panDistance
}
// Clamp camera position.
padding := world.TileSize * world.CamScale / 2
halfWidth := (world.ScreenWidth/2)/world.CamScale - padding
halfHeight := (world.ScreenHeight/2)/world.CamScale - padding
if world.CamX < halfWidth {
world.CamX = halfWidth
} else if world.CamX > (world.TileSize*world.MapSize)-halfWidth {
world.CamX = (world.TileSize * world.MapSize) - halfWidth
}
if world.CamY < halfHeight {
world.CamY = halfHeight
} else if world.CamY > (world.TileSize*world.MapSize)-halfHeight {
world.CamY = (world.TileSize * world.MapSize) - halfHeight
}
if inpututil.IsKeyJustPressed(ebiten.KeyV) && ebiten.IsKeyPressed(ebiten.KeyControl) {
world.Debug++
if world.Debug > 2 {
world.Debug = 0
}
}
if inpututil.IsMouseButtonJustPressed(ebiten.MouseButtonLeft) {
tx, ty := world.ScreenCoordinatesToPath(world.CursorX, world.CursorY)
from := world.Map[world.PathTileIndex(1, 1)]
to := world.Map[world.PathTileIndex(tx, ty)]
path, _, _ := astar.Path(from, to)
world.MapPath = nil
for _, p := range path {
t := p.(world.Tile)
world.MapPath = append(world.MapPath, [2]float64{t.X, t.Y})
}
}
return nil
}
func (r *HandleInput) Draw(e gohan.Entity, screen *ebiten.Image) error {
return gohan.ErrUnregister
}