examples: game-controller: Add left/right trigger rendering.
[chickadee.git] / examples / game-controller.scm
1 (use-modules (chickadee)
2 (chickadee math vector)
3 (chickadee render color)
4 (chickadee render font)
5 (chickadee render sprite)
6 (chickadee render texture)
7 (ice-9 match))
8
9 (define controller #f)
10 (define atlas #f)
11 (define button-icons
12 `((dpad-down ,(vec2 110.0 140.0) 7 25)
13 (dpad-right ,(vec2 170.0 210.0) 9 27)
14 (dpad-left ,(vec2 50.0 210.0) 8 26)
15 (dpad-up ,(vec2 110.0 280.0) 6 24)
16 (a ,(vec2 450.0 140.0) 0 18)
17 (b ,(vec2 510.0 210.0) 1 19)
18 (x ,(vec2 390.0 210.0) 2 20)
19 (y ,(vec2 450.0 280.0) 3 21)
20 (back ,(vec2 190.0 330.0) 11 29)
21 (guide ,(vec2 280.0 330.0) 12 30)
22 (start ,(vec2 370.0 330.0) 10 28)
23 (left-stick ,(vec2 110.0 20.0) 13 31)
24 (right-stick ,(vec2 450.0 20.0) 13 31)
25 (left-shoulder ,(vec2 110.0 390.0) 4 22)
26 (right-shoulder ,(vec2 450.0 390.0) 5 23)))
27 (define trigger-icons
28 `((trigger-left ,(vec2 10.0 390.0) 22)
29 (trigger-right ,(vec2 550.0 390.0) 23)))
30 (define no-controller-msg "no controller detected :'(")
31 (define no-controller-msg-pos #f)
32 (define controller-name-pos #f)
33
34 (define (center-text text)
35 (/ (- 640.0 (font-line-width (default-font) text)) 2.0))
36
37 (define (load)
38 (set! no-controller-msg-pos (vec2 (center-text no-controller-msg) 240.0))
39 (set! atlas (split-texture (load-image "images/controller-buttons.png")
40 80 80)))
41
42 (define (controller-add new-controller)
43 (set! controller (or controller new-controller))
44 (set! controller-name-pos
45 (vec2 (center-text (controller-name controller)) 440.0)))
46
47 (define (draw alpha)
48 (if controller
49 (with-batched-sprites
50 (draw-text (controller-name controller) controller-name-pos)
51 (for-each (match-lambda
52 ((axis p tile)
53 (let ((alpha (controller-axis controller axis)))
54 (draw-sprite (texture-atlas-ref atlas tile) p
55 #:tint (color 1.0 1.0 1.0 alpha)))))
56 trigger-icons)
57 (for-each (match-lambda
58 (((and (or 'left-stick 'right-stick) button)
59 p released pressed)
60 (let ((pressed? (controller-button-pressed? controller
61 button))
62 (x (controller-axis controller
63 (if (eq? button 'left-stick)
64 'left-x
65 'right-x)))
66 (y (controller-axis controller
67 (if (eq? button 'left-stick)
68 'left-y
69 'right-y))))
70 (draw-sprite (texture-atlas-ref atlas released)
71 p)
72 (when (or pressed? (not (zero? x)) (not (zero? y)))
73 (draw-sprite (texture-atlas-ref atlas pressed)
74 (vec2+ p (vec2 (* x 16.0) (* y -16.0)))))))
75 ((button p released pressed)
76 (let ((pressed? (controller-button-pressed? controller
77 button)))
78 (draw-sprite (texture-atlas-ref
79 atlas
80 (if pressed? pressed released))
81 p))))
82 button-icons))
83 (draw-text no-controller-msg no-controller-msg-pos)))
84
85 (run-game #:load load #:draw draw #:controller-add controller-add)