project-ely/internal/game/player/player.go

69 lines
1.8 KiB
Go

package player
import (
"context"
"time"
"git.wisellama.rocks/Project-Ely/project-ely/internal/game/entity/command"
"github.com/veandco/go-sdl2/sdl"
)
type InputHandler interface {
Keystate(keycode sdl.Keycode) bool
}
// A player represents a collection of stuff controlled by the user's input.
// It contains the camera used to view the world,
// the viewport for the part of the screen to draw to (splitscreen support),
// as well as the entity the player is currently controlling.
type player struct {
ctx context.Context
timeout time.Duration
inputHandler InputHandler
entityChan chan command.Command
}
func NewPlayer(ctx context.Context, inputHandler InputHandler) *player {
defaultTimeout := time.Second
p := player{
ctx: ctx,
timeout: defaultTimeout,
inputHandler: inputHandler,
}
return &p
}
func (p *player) SetEntityChan(e chan command.Command) {
p.entityChan = e
}
func (p *player) Update() error {
// Speed
if p.inputHandler.Keystate(sdl.K_LSHIFT) {
p.entityChan <- command.NewCommand(command.SET_SPEED, 4)
} else {
p.entityChan <- command.NewCommand(command.SET_SPEED, 2)
}
// Move X
if p.inputHandler.Keystate(sdl.K_d) {
p.entityChan <- command.NewCommand(command.MOVE_X, 1.0)
} else if p.inputHandler.Keystate(sdl.K_a) {
p.entityChan <- command.NewCommand(command.MOVE_X, -1.0)
} else if !p.inputHandler.Keystate(sdl.K_d) && !p.inputHandler.Keystate(sdl.K_a) {
p.entityChan <- command.NewCommand(command.MOVE_X, 0.0)
}
// Move Y
if p.inputHandler.Keystate(sdl.K_w) {
p.entityChan <- command.NewCommand(command.MOVE_Y, 1.0)
} else if p.inputHandler.Keystate(sdl.K_s) {
p.entityChan <- command.NewCommand(command.MOVE_Y, -1.0)
} else if !p.inputHandler.Keystate(sdl.K_w) && !p.inputHandler.Keystate(sdl.K_s) {
p.entityChan <- command.NewCommand(command.MOVE_Y, 0.0)
}
return nil
}