跳转至

Module 3 UI, Interaction, Game Manager, Gradual Changes, Autonomous Behavior

Coverage

Unity specific skills you will need, practice, and demonstrate include:

·         User Interface

o   Sharing the editor between the GameObject world and the UI coordinate system

o   Working with UI RectTransform

·         Packages: create and import

Concepts you will explore and understand include

·         The lerp function: gradual rotation and chasing

·         Simple implementation of a finite state machine

·         Randomness and simple examples in games (again)

1.      User Interface and Packages: Example based on Module-2 Example-4

o    Run Behavior: press-space bar to launch egg at slider-bar-value interval

o    Packet Import:

§  Assets èImport Package: select SliderWithEcho.unitypackage

§  From the github look for ClassExample/Packages

§  PreFab: UI-SliderWithEcho

§  Scripts/UI/SliderWithEcho.cs

§  To create your own package, do the reverse: AssetsèExport and select the appropriate components (remember to select the necessary scripts)

o    UI: Using the imported package

§  Remember, first your scene must have a Canvas (create by: UIàCanvas)

§  To use: drag SliderWithEcho pre-fab into the Canvas:

1.      Align anchor: lower-left

§  Rename to: SpawnRate

§  Must configure: (Select SpawnRate and look in the Inspector Window)

1.      mLabelText

2.      SliderValue: (this is a Text UI object)

1.      Customize the text detail, e.g., color

3.      SliderBar (in the Slider component)

1.      Set:   Min Value, Max Value, Init Value

§  Careful: when adjusting positions of the SliderWithEcho object, do not adjust the children positions!

o    GreenArrowBehavior: reference an SliderWithEcho

§  In the editor: drag the entire SliderWithEcho (SpawnRate) to the GreenArrowBehaivor object

§  The value() of SpwanRate is how many seconds to wait in between spawning new eggs

§  Note: Time.time amount of seconds elapsed since the beginning of the game

o    Learned:

§  Almost all Unity specific:

§  Time.time: time (in seconds) after game began

§  Package: import/export of prefab watch to check all dependent components

§  Note the logic in GreeArrowBehavior::Update() on check for spawn rate.

o    Alternate implementation:

§  SpawnRateèSliderBar has a call back (event handler)

§  Can define a function in GreenArrowBehavior and add the function here.

1.      Pros: Receives value change via event, no need to refer in update()

2.      Cons: Implicit references (via event service functions), can be challenging to figure out all event handlers.

§  I usually poll UI events in Update() function.

§  Exercise:

§  Implement this alternative.

  • WARNING: Text echo is not kind, default horizontal overflow is set to truncate, meaning, if a text is too long (e.g., number with many precision digits), the number will not show! Try it!!

  • UI-Canvas àSpawnRateàSliderValue: under Text (Script)

§  A wrap in the horizontal and truncate in the vertical may result in part of the message not shown!

§  Look for Horizontal Overflow, try different settings!

  1. Cool Down Bar: simple continuation from the previous example

  2. Run Behavior: press-space bar to launch egg at slider-bar-value interval and watch the cool down bar

  3. Package Import:

  4. Assets èImport Package: select CoolDownBar.unitypackage

  5. From the github look for ClassExample/Packages

  6. PreFab: UI-CoolDownBar

  7. Scripts/UI/CoolDownBar.cs

  8. UI: Using the imported package

  9. Remember: you must have a Canvas (to create: UIàCanvas)

  10. Optional: set the value of Sec_To_Cool_Down

  11. Select CoolDownBar, and look for the CoolDownBar.cs component

  12. GreenArrowBehavior: reference an SliderWithEcho, and CoolDownBar

  13. In the editor: connect CoolDownBar UI to the instance variable

  14. Note: the re-spawn time restriction logic is now hidden

  15. Learned: Importance and beauty of OO, CoolDownBar hides spawn rate logic from GreenArrowBehavior!

  16. Gradual Rotation and Chasing

  17. Run Behavior:

  18. WASD: move the egg

  19. UpArrow chase after the egg
  20. TurnRate:  (be careful, slider bar may keep focus of mouse, click somewhere else to un-focus)

  21. 0 does not turn towards egg

  22. 1 always point at egg
  23. 0 < rate < 1: turns gradually from very slow (values close to 0), to very quick (values close to 1)

  24. Egg: WASD_Movement: trivial behavior

  25. GreenArrowBehavior:

  26. Public variables

  27. TurnRate: connects to the slider

  28. Target: connects to the egg

  29. PointAtPosition(): function

  30. Pointing the transform.up towards any given position

  31. Incremental rotation of transform.up to align with V

  32. Watch out, if transform.up and V are pointing in perfect opposite directions, the turning does not work.

  33. Update()

  34. Calls PointAtPosition()

  35. Move in the direction of transform.up

  36. In game object movement consideration

  37. Easy: Direct control: you control the position of an object

  38. Less Easy: Indirect control: e.g., you control the velocity of an object
  39. Obey the rules of physics: Indirect control in the world with physics (gravity and potentials for collisions), you configure the physics to control the object movement
  40. Follow your own algorithm: No control: autonomous (as in this case)

  41. Learned:

  42. Gradual rotation: Vector3.lerpUnclamped()

  43. The PointAtPosition() function

  44. Quite reusable

  45. In-game object movement considerations

  46. Autonomous Movement with Randomness:

  47. Run Behavior:

  48. Watch the green arrow chases the egg, when gets close, egg spawn in a new position in the pinkish area

  49. SliderBar changes the pinkish area size (% of world bound size)
  50. N-Key: to spawn a new GreenArrow
  51. H-Key: to hide the egg
  52. Try: spawn 20 arrows, and then hide the egg, see a bunch of patrolling arrows?!

  53. Scene Setting

  54. MainCamera: has CameraSupport: for setting and testing bounds

  55. Child: GameManager: empty game object for hanging the singleton GameManager

  56. TargetBoundBox (pinkish)

  57. This box is behind the green arrow (with larger Z-position values, the larger the Z the more behind).

  58. Be careful: camera settings only allows z values of up to 1000: MainCamera.Far

  59. GreenArrow: chases after the egg

  60. GameManager:

  61. Awake():

  62. Initialize must be done before GreenArrowBehavior::Start()!

  63. Has reference

  64. CameraSupport: to compute world bound and target bound

  65. TargetBoundBox: to be scaled into the size user specified
  66. TargetBoundSlider: child of UI-Canvas, the slider bar

  67. GetTargetBound: computes the percentage of a given bound

  68. GreenArrowBehavior:

  69. ComputeNewTargetPosition: a random target position within a given bound

  70. Vector.Distance(): Notice this function, convenient to use

  71. Learned:

  72. Compute the percentage of a given bound (GameManager::GetTargetBound())

  73. Random position in a bound (GreenArrow::ComputeNewTargetPosition())
  74. Distance between two game objects: Vector3::Distance() function
  75. Game object positions: z values are important

  76. Front is smaller z, behind/far is larger z

  77. SHOULD NOT change the z-value of an object during game play

  78. May cause “flipping” rotation

  79. E.g., change the z value of Target to e.g., 1.0f and observe arrow flips

  80. SliderBar callback function

  81. Efficient, only compute when there are changes

  82. Edited in the UI

  83. Finite State Machine

  84. Run Behavior:

  85. Move the arrow with WASD

  86. Touch the plane to trigger fixed behavior

  87. Finite State Machine: Simple state on the Plane. Here is the state transition definition

  88. Normally, nothing, when collision

  89. enlarge for 120 frames
  90. rotate CW fast for 80 frames
  91. rotate CCW for 80 frames
  92. shrink for 120 frames
  93. return to resting
  94. Note: in our context, if an operation does not need time, it is NOT a state. All states, in the FSM needs more than one update() cycle.

  95. Implementation Keys:

  96. Draw the state diagram!!

  97. Instance variables for state definition and transition
  98. Enum for individual states
  99. Case statement in update()
  100. State service: Each state is a separate function!

  101. As states become complicated, they can be defined as instance of different classes (with shared base class)

  102. Organization

  103. Partial class (different files implementing the same class)

  104. Plane.cs  and Plane_FSM.cs

  105. Each contains separate details!

  106. Learned:

  107. Finite State Machine: important to

  108. Draw out ALL states, and

  109. Define all possible input and state transitions

  110. Implementation key: review the above!

  111. Relatively straightforward to define simple repetitive autonomous behaviors!
  112. C# Partial class: to help separate source code into different files for organization

  113. FSM + Randomness

  114. Run Behavior:

  115. All planes cycles through states without going into resting

  116. Random enlarge and rotation periods (turn constants into variables)
  117. After a while, look rather random?

  118. GameManager: hanging off MainCamera

  119. Creates all the planes at startup

  120. Plane:

  121. Randomness: in the Start() function, sets the number of frames in scale/rotate states to be random

  122. Learned:

  123. Beauty and simplicity of random

§  Ease of expansion when well abstracted

  1. Orbiting

  2. Run Behavior

  3. Eggs orbits around hero

  4. No UI support, must change from the editor, try

  5. Select Hero in Editor and move hero around (egg follows)

  6. Select Egg and change

  7. Orbit Radius

  8. Orbit Speed

  9. Scene:

  10. Egg is the satellite

  11. OrbitControlàHostXform points to Hero’s xform

  12. OrbitControl.cs on the Egg (can be on any objects):

  13. Literally 3-lines of code!

  14. Learned:

  15. Nice to know quaternion 😊.