86 lines
1.8 KiB
Go
86 lines
1.8 KiB
Go
package player
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"git.wisellama.rocks/Project-Ely/project-ely/internal/channels"
|
|
rl "github.com/gen2brain/raylib-go/raylib"
|
|
)
|
|
|
|
type PhysicalObject interface {
|
|
SetVelocity(vel rl.Vector2)
|
|
}
|
|
|
|
// 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
|
|
|
|
controlledObject PhysicalObject
|
|
}
|
|
|
|
func NewPlayer(ctx context.Context) *player {
|
|
defaultTimeout := time.Second
|
|
|
|
p := player{
|
|
ctx: ctx,
|
|
timeout: defaultTimeout,
|
|
}
|
|
return &p
|
|
}
|
|
|
|
func (p *player) SetControlledObject(c PhysicalObject) {
|
|
p.controlledObject = c
|
|
}
|
|
|
|
func (p *player) Update() {
|
|
var (
|
|
up bool
|
|
down bool
|
|
left bool
|
|
right bool
|
|
fast bool
|
|
)
|
|
channels.RL.Do(func() {
|
|
fast = rl.IsKeyDown(rl.KeyLeftShift)
|
|
left = rl.IsKeyDown(rl.KeyA) || rl.IsKeyDown(rl.KeyLeft)
|
|
right = rl.IsKeyDown(rl.KeyD) || rl.IsKeyDown(rl.KeyRight)
|
|
up = rl.IsKeyDown(rl.KeyW) || rl.IsKeyDown(rl.KeyUp)
|
|
down = rl.IsKeyDown(rl.KeyS) || rl.IsKeyDown(rl.KeyDown)
|
|
})
|
|
|
|
baseVel := rl.Vector2{X: 1.0, Y: 1.0}
|
|
velocity := rl.Vector2{X: 0.0, Y: 0.0}
|
|
|
|
// Move horizontal
|
|
if right {
|
|
velocity.X = baseVel.X
|
|
} else if left {
|
|
velocity.X = baseVel.X * -1
|
|
}
|
|
|
|
// Move vertical
|
|
if up {
|
|
velocity.Y = baseVel.Y
|
|
} else if down {
|
|
velocity.Y = baseVel.Y * -1
|
|
}
|
|
|
|
// If we're moving diagonal, normalize the vector to avoid weird diagonal super-speed
|
|
if velocity.X != 0 || velocity.Y != 0 {
|
|
velocity = rl.Vector2Normalize(velocity)
|
|
}
|
|
|
|
// Faster speed
|
|
if fast {
|
|
velocity.X *= 2
|
|
velocity.Y *= 2
|
|
}
|
|
|
|
p.controlledObject.SetVelocity(velocity)
|
|
}
|