55 "embed"
66 "io/fs"
77 "log"
8+ "math"
89 "math/rand/v2"
910 "time"
1011
@@ -30,6 +31,7 @@ const (
3031 action_down
3132 sample_rate = 48000
3233 anim_rate = time .Second / 8 // 8fps pixel art animation (looping 3-frame walk cycles)
34+ player_speed = 4
3335)
3436
3537var (
@@ -61,27 +63,39 @@ type Player struct {
6163 rect * resolv.ConvexPolygon // DRY violation w/ x,y -- should we solely use the collision lib rect?
6264}
6365
66+ func (p * Player ) NormalizeVelocity () {
67+ length_squared := math .Sqrt (p .dx * p .dx + p .dy * p .dy )
68+ if length_squared == 0 {
69+ return
70+ } else {
71+ p .dx *= player_speed / length_squared
72+ p .dy *= player_speed / length_squared
73+ }
74+ }
75+
6476func (g * Game ) Update () error {
6577 g .input_system .Update ()
6678 was_walking := g .player .dx != 0 || g .player .dy != 0
6779
6880 if g .player_input .ActionIsPressed (action_left ) {
69- g .player .dx = - 4
81+ g .player .dx = - player_speed
7082 } else if g .player_input .ActionIsPressed (action_right ) {
71- g .player .dx = 4
83+ g .player .dx = player_speed
7284 } else {
7385 g .player .dx = 0
7486 }
7587
7688 if g .player_input .ActionIsPressed (action_up ) {
77- g .player .dy = - 4
89+ g .player .dy = - player_speed
7890 } else if g .player_input .ActionIsPressed (action_down ) {
79- g .player .dy = 4
91+ g .player .dy = player_speed
8092 } else {
8193 g .player .dy = 0
8294 }
8395 is_walking := g .player .dx != 0 || g .player .dy != 0
8496
97+ g .player .NormalizeVelocity ()
98+
8599 g .player .x += g .player .dx
86100 g .player .y += g .player .dy
87101 g .player .rect .Move (g .player .dx , g .player .dy )
0 commit comments