krz/daybyday

iOS learning games for young children: days, months, seasons, numbers, letters, animals and more. education ios kids swift https://krz.sh/apps/daybyday/

DayByDay/Mascot/MascotMotion.swift

main
daybyday/DayByDay/Mascot/MascotMotion.swift history · blame · raw

63 lines · 2084 bytes

2 symbols in this file
  • pose function, line 31
  • still function, line 52
 1//
 2//  MascotMotion.swift
 3//  DayByDay
 4//
 5
 6import Foundation
 7
 8/// Where the mascot's parts are at one moment.
 9nonisolated struct MascotPose: Equatable {
10    /// Up and down drift, as a fraction of the size; up is negative.
11    var bob: Double
12    /// Cheer hop, as a fraction of the size; up is negative.
13    var hop: Double
14    /// 1 open, 0.1 shut.
15    var eyeOpen: Double
16    /// Degrees the raised wing is lifted.
17    var wing: Double
18    /// Degrees the whole owl leans.
19    var tilt: Double
20    /// 0 closed, 1 wide open.
21    var beakOpen: Double
22}
23
24/// Subtle motion for each mood: a slow bob, a blink, a hop when cheering, a
25/// wave, and a talking beak when asking.
26nonisolated enum MascotMotion {
27    static let blinkCycle = 3.8
28    static let blinkLength = 0.14
29
30    /// The pose `t` seconds after the mood began.
31    static func pose(_ mood: MascotMood, at t: TimeInterval) -> MascotPose {
32        let t = max(0, t)
33        var pose = still(mood)
34        pose.bob = -0.012 * (1 - cos(2 * .pi * t / 2.6)) / 2
35        if mood != .cheering, t.truncatingRemainder(dividingBy: blinkCycle) >= blinkCycle - blinkLength {
36            pose.eyeOpen = 0.1
37        }
38        switch mood {
39        case .cheering:
40            if t.truncatingRemainder(dividingBy: 4) < 1.6 { pose.hop = -0.06 * abs(sin(.pi * t / 0.4)) }
41        case .waving:
42            if t.truncatingRemainder(dividingBy: 5) < 2.1 { pose.wing = 135 + 15 * sin(2 * .pi * t / 0.7) }
43        case .asking:
44            pose.beakOpen = 0.5 + 0.5 * abs(sin(.pi * t / 0.22))
45        case .idle, .puzzled:
46            break
47        }
48        return pose
49    }
50
51    /// The mood's pose with no motion, for Reduce Motion.
52    static func still(_ mood: MascotMood) -> MascotPose {
53        var pose = MascotPose(bob: 0, hop: 0, eyeOpen: 1, wing: 0, tilt: 0, beakOpen: 0)
54        switch mood {
55        case .idle: break
56        case .asking: pose.tilt = 4; pose.beakOpen = 1
57        case .cheering: pose.wing = 130
58        case .puzzled: pose.tilt = -10
59        case .waving: pose.wing = 135
60        }
61        return pose
62    }
63}