Debian Codegraph @

examples/third_person_navigation/code/gameviewplay.pas

raw
1 {
2 Copyright 2020-2023 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Main "playing game" view, where most of the game logic takes place. }
17 unit GameViewPlay;
18
19 {.$define CASTLE_UNFINISHED_CHANGE_TRANSFORMATION_BY_FORCE}
20
21 interface
22
23 uses Classes,
24 CastleComponentSerialize, CastleUIControls, CastleControls,
25 CastleKeysMouse, CastleViewport, CastleScene, CastleVectors, CastleCameras,
26 CastleTransform, CastleInputs, CastleThirdPersonNavigation, CastleDebugTransform,
27 CastleSceneCore,
28 GameEnemy;
29
30 type
31 { Main "playing game" view, where most of the game logic takes place. }
32 TViewPlay = class(TCastleView)
33 published
34 { Components designed using CGE editor.
35 These fields will be automatically initialized at Start. }
36 LabelFps: TCastleLabel;
37 MainViewport: TCastleViewport;
38 ThirdPersonNavigation: TCastleThirdPersonNavigation;
39 SceneAvatar, SceneLevel: TCastleScene;
40 AvatarRigidBody: TCastleRigidBody;
41 CheckboxCameraFollows: TCastleCheckbox;
42 CheckboxAimAvatar: TCastleCheckbox;
43 CheckboxDebugAvatarColliders: TCastleCheckbox;
44 CheckboxImmediatelyFixBlockedCamera: TCastleCheckbox;
45 SliderAirRotationControl: TCastleFloatSlider;
46 SliderAirMovementControl: TCastleFloatSlider;
47 ButtonChangeTransformationAuto,
48 ButtonChangeTransformationDirect,
49 ButtonChangeTransformationVelocity,
50 ButtonChangeTransformationForce: TCastleButton;
51 private
52 { Enemies behaviors }
53 Enemies: TEnemyList;
54
55 DebugAvatar: TDebugTransform;
56 { Change things after ThirdPersonNavigation.ChangeTransformation changed. }
57 procedure UpdateAfterChangeTransformation;
58 procedure ChangeCheckboxCameraFollows(Sender: TObject);
59 procedure ChangeCheckboxAimAvatar(Sender: TObject);
60 procedure ChangeCheckboxDebugAvatarColliders(Sender: TObject);
61 procedure ChangeCheckboxImmediatelyFixBlockedCamera(Sender: TObject);
62 procedure ChangeAirRotationControl(Sender: TObject);
63 procedure ChangeAirMovementControl(Sender: TObject);
64 procedure ClickChangeTransformationAuto(Sender: TObject);
65 procedure ClickChangeTransformationDirect(Sender: TObject);
66 procedure ClickChangeTransformationVelocity(Sender: TObject);
67 procedure ClickChangeTransformationForce(Sender: TObject);
68 public
69 constructor Create(AOwner: TComponent); override;
70 procedure Start; override;
71 procedure Stop; override;
72 procedure Update(const SecondsPassed: Single; var HandleInput: Boolean); override;
73 function Press(const Event: TInputPressRelease): Boolean; override;
74 end;
75
76 var
77 ViewPlay: TViewPlay;
78
79 implementation
80
81 uses SysUtils, Math, StrUtils,
82 CastleSoundEngine, CastleLog, CastleStringUtils, CastleFilesUtils, CastleUtils,
83 GameViewMenu;
84
85 { TViewPlay ----------------------------------------------------------------- }
86
87 constructor TViewPlay.Create(AOwner: TComponent);
88 begin
89 inherited;
90 DesignUrl := 'castle-data:/gameviewplay.castle-user-interface';
91 end;
92
93 procedure TViewPlay.Start;
94 var
95 SoldierScene: TCastleScene;
96 Enemy: TEnemy;
97 I: Integer;
98 begin
99 inherited;
100
101 { Create TEnemy instances, add them to Enemies list }
102 Enemies := TEnemyList.Create(true);
103 for I := 1 to 4 do
104 begin
105 SoldierScene := DesignedComponent('SceneSoldier' + IntToStr(I)) as TCastleScene;
106 { Below using nil as Owner of TEnemy, as the Enemies list already "owns"
107 instances of this class, i.e. it will free them. }
108 Enemy := TEnemy.Create(nil);
109 SoldierScene.AddBehavior(Enemy);
110 Enemies.Add(Enemy);
111 end;
112
113 { synchronize state -> UI }
114 SliderAirRotationControl.Value := ThirdPersonNavigation.AirRotationControl;
115 SliderAirMovementControl.Value := ThirdPersonNavigation.AirMovementControl;
116 UpdateAfterChangeTransformation;
117
118 CheckboxCameraFollows.OnChange := {$ifdef FPC}@{$endif} ChangeCheckboxCameraFollows;
119 CheckboxAimAvatar.OnChange := {$ifdef FPC}@{$endif} ChangeCheckboxAimAvatar;
120 CheckboxDebugAvatarColliders.OnChange := {$ifdef FPC}@{$endif} ChangeCheckboxDebugAvatarColliders;
121 CheckboxImmediatelyFixBlockedCamera.OnChange := {$ifdef FPC}@{$endif} ChangeCheckboxImmediatelyFixBlockedCamera;
122 SliderAirRotationControl.OnChange := {$ifdef FPC}@{$endif} ChangeAirRotationControl;
123 SliderAirMovementControl.OnChange := {$ifdef FPC}@{$endif} ChangeAirMovementControl;
124 ButtonChangeTransformationAuto.OnClick := {$ifdef FPC}@{$endif} ClickChangeTransformationAuto;
125 ButtonChangeTransformationDirect.OnClick := {$ifdef FPC}@{$endif} ClickChangeTransformationDirect;
126 ButtonChangeTransformationVelocity.OnClick := {$ifdef FPC}@{$endif} ClickChangeTransformationVelocity;
127 ButtonChangeTransformationForce.OnClick := {$ifdef FPC}@{$endif} ClickChangeTransformationForce;
128
129 {$ifndef CASTLE_UNFINISHED_CHANGE_TRANSFORMATION_BY_FORCE}
130 { Hide UI to test ChangeTransformation = ctForce, it is not finished now,
131 not really useful for normal usage. }
132 ButtonChangeTransformationForce.Exists := false;
133 {$endif}
134
135 { This configures SceneAvatar.Middle point, used for shooting.
136 In case of old physics (ChangeTransformation = ctDirect) this is also the center
137 of SceneAvatar.CollisionSphereRadius. }
138 SceneAvatar.MiddleHeight := 0.9;
139
140 { Configure some parameters of old simple physics,
141 these only matter when SceneAvatar.Gravity = true.
142 Don't use these deprecated things if you don't plan to use ChangeTransformation = ctDirect! }
143 SceneAvatar.GrowSpeed := 10.0;
144 SceneAvatar.FallSpeed := 10.0;
145 { When avatar collides as sphere it can climb stairs,
146 because legs can temporarily collide with objects. }
147 SceneAvatar.CollisionSphereRadius := 0.5;
148
149 { Visualize SceneAvatar bounding box, sphere, middle point, direction etc. }
150 DebugAvatar := TDebugTransform.Create(FreeAtStop);
151 DebugAvatar.Parent := SceneAvatar;
152
153 { Configure ThirdPersonNavigation keys (for now, we don't expose doing this in CGE editor). }
154 ThirdPersonNavigation.Input_LeftStrafe.Assign(keyQ);
155 ThirdPersonNavigation.Input_RightStrafe.Assign(keyE);
156 ThirdPersonNavigation.MouseLook := true; // TODO: assigning it from editor doesn't make mouse hidden in mouse look
157 ThirdPersonNavigation.Init;
158 end;
159
160 procedure TViewPlay.Stop;
161 begin
162 FreeAndNil(Enemies);
163 inherited;
164 end;
165
166 procedure TViewPlay.Update(const SecondsPassed: Single; var HandleInput: Boolean);
167
168 // Test: use this to make AimAvatar only when *holding* right mouse button.
169 (*
170 procedure UpdateAimAvatar;
171 begin
172 if buttonRight in Container.MousePressed then
173 ThirdPersonNavigation.AimAvatar := aaHorizontal
174 else
175 ThirdPersonNavigation.AimAvatar := aaNone;
176
177 { In this case CheckboxAimAvatar only serves to visualize whether
178 the right mouse button is pressed now. }
179 CheckboxAimAvatar.Checked := ThirdPersonNavigation.AimAvatar <> aaNone;
180 end;
181 *)
182
183 begin
184 inherited;
185 { This virtual method is executed every frame (many times per second). }
186 LabelFps.Caption := 'FPS: ' + Container.Fps.ToString;
187 // UpdateAimAvatar;
188 end;
189
190 function TViewPlay.Press(const Event: TInputPressRelease): Boolean;
191
192 function AvatarRayCast: TCastleTransform;
193 var
194 RayCastResult: TPhysicsRayCastResult;
195 begin
196 RayCastResult := AvatarRigidBody.PhysicsRayCast(
197 SceneAvatar.Middle,
198 SceneAvatar.Direction
199 );
200 Result := RayCastResult.Transform;
201
202 { Alternative version, using Items.PhysicsRayCast
203 (everything in world space coordinates).
204 This works equally well, showing it here just for reference.
205
206 RayCastResult := MainViewport.Items.PhysicsRayCast(
207 SceneAvatar.Parent.LocalToWorld(SceneAvatar.Middle),
208 SceneAvatar.Parent.LocalToWorldDirection(SceneAvatar.Direction),
209 MaxSingle,
210 AvatarRigidBody
211 );
212 Result := RayCastResult.Transform;
213 }
214
215 (* Alternative versions, using old physics,
216 see https://castle-engine.io/physics#_old_system_for_collisions_and_gravity .
217 They still work (even when you also use new physics).
218
219 if not AvatarRigidBody.Exists then
220 begin
221 { SceneAvatar.RayCast tests a ray collision,
222 ignoring the collisions with SceneAvatar itself (so we don't detect our own
223 geometry as colliding). }
224 Result := SceneAvatar.RayCast(SceneAvatar.Middle, SceneAvatar.Direction);
225 end else
226 begin
227 { When physics engine is working, we should not toggle Exists multiple
228 times in a single frame, which makes the curent TCastleTransform.RayCast not good.
229 So use Items.WorldRayCast, and secure from "hitting yourself" by just moving
230 the initial ray point by 0.5 units. }
231 Result := MainViewport.Items.WorldRayCast(
232 SceneAvatar.Middle + SceneAvatar.Direction * 0.5, SceneAvatar.Direction);
233 end;
234 *)
235 end;
236
237 var
238 HitByAvatar: TCastleTransform;
239 HitEnemy: TEnemy;
240 begin
241 Result := inherited;
242 if Result then Exit; // allow the ancestor to handle keys
243
244 { This virtual method is executed when user presses
245 a key, a mouse button, or touches a touch-screen.
246
247 Note that each UI control has also events like OnPress and OnClick.
248 These events can be used to handle the "press", if it should do something
249 specific when used in that UI control.
250 The TViewPlay.Press method should be used to handle keys
251 not handled in children controls.
252 }
253
254 if Event.IsMouseButton(buttonLeft) then
255 begin
256 SoundEngine.Play(SoundEngine.SoundFromName('shoot_sound'));
257
258 { We clicked on enemy if
259 - HitByAvatar indicates we hit something
260 - It has a behavior of TEnemy. }
261 HitByAvatar := AvatarRayCast;
262 if (HitByAvatar <> nil) and
263 (HitByAvatar.FindBehavior(TEnemy) <> nil) then
264 begin
265 HitEnemy := HitByAvatar.FindBehavior(TEnemy) as TEnemy;
266 HitEnemy.Hurt;
267 end;
268
269 Exit(true);
270 end;
271
272 if Event.IsMouseButton(buttonRight) then
273 begin
274 ThirdPersonNavigation.MouseLook := not ThirdPersonNavigation.MouseLook;
275 Exit(true);
276 end;
277
278 if Event.IsKey(keyF5) then
279 begin
280 Container.SaveScreenToDefaultFile;
281 Exit(true);
282 end;
283
284 if Event.IsKey(keyEscape) then
285 begin
286 Container.View := ViewMenu;
287 Exit(true);
288 end;
289 end;
290
291 procedure TViewPlay.ChangeCheckboxCameraFollows(Sender: TObject);
292 begin
293 ThirdPersonNavigation.CameraFollows := CheckboxCameraFollows.Checked;
294 end;
295
296 procedure TViewPlay.ChangeCheckboxAimAvatar(Sender: TObject);
297 begin
298 if CheckboxAimAvatar.Checked then
299 ThirdPersonNavigation.AimAvatar := aaHorizontal
300 else
301 ThirdPersonNavigation.AimAvatar := aaNone;
302
303 { The 3rd option, aaFlying, doesn't make sense for this case,
304 when avatar walks on the ground and has Gravity = true. }
305 end;
306
307 procedure TViewPlay.ChangeCheckboxDebugAvatarColliders(Sender: TObject);
308 begin
309 DebugAvatar.Exists := CheckboxDebugAvatarColliders.Checked;
310 end;
311
312 procedure TViewPlay.ChangeCheckboxImmediatelyFixBlockedCamera(Sender: TObject);
313 begin
314 ThirdPersonNavigation.ImmediatelyFixBlockedCamera := CheckboxImmediatelyFixBlockedCamera.Checked;
315 end;
316
317 procedure TViewPlay.ChangeAirRotationControl(Sender: TObject);
318 begin
319 ThirdPersonNavigation.AirRotationControl := SliderAirRotationControl.Value;
320 end;
321
322 procedure TViewPlay.ChangeAirMovementControl(Sender: TObject);
323 begin
324 ThirdPersonNavigation.AirMovementControl := SliderAirMovementControl.Value;
325 end;
326
327 procedure TViewPlay.UpdateAfterChangeTransformation;
328 begin
329 ButtonChangeTransformationAuto.Pressed := ThirdPersonNavigation.ChangeTransformation = ctAuto;
330 ButtonChangeTransformationDirect.Pressed := ThirdPersonNavigation.ChangeTransformation = ctDirect;
331 ButtonChangeTransformationVelocity.Pressed := ThirdPersonNavigation.ChangeTransformation = ctVelocity;
332 {$ifdef CASTLE_UNFINISHED_CHANGE_TRANSFORMATION_BY_FORCE}
333 ButtonChangeTransformationForce.Pressed := ThirdPersonNavigation.ChangeTransformation = ctForce;
334 {$endif}
335
336 { ctDirect requires to set up gravity without physics engine,
337 using deprecated TCastleTransform.Gravity.
338 See https://castle-engine.io/physics#_old_system_for_collisions_and_gravity }
339 AvatarRigidBody.Exists := ThirdPersonNavigation.ChangeTransformation <> ctDirect;
340
341 { Gravity means that object tries to maintain a constant height
342 (SceneAvatar.PreferredHeight) above the ground.
343 GrowSpeed means that object raises properly (makes walking up the stairs work).
344 FallSpeed means that object falls properly (makes walking down the stairs,
345 falling down pit etc. work). }
346 SceneAvatar.Gravity := not AvatarRigidBody.Exists;
347 end;
348
349 procedure TViewPlay.ClickChangeTransformationAuto(Sender: TObject);
350 begin
351 ThirdPersonNavigation.ChangeTransformation := ctAuto;
352 UpdateAfterChangeTransformation;
353 end;
354
355 procedure TViewPlay.ClickChangeTransformationDirect(Sender: TObject);
356 begin
357 ThirdPersonNavigation.ChangeTransformation := ctDirect;
358 UpdateAfterChangeTransformation;
359 end;
360
361 procedure TViewPlay.ClickChangeTransformationVelocity(Sender: TObject);
362 begin
363 ThirdPersonNavigation.ChangeTransformation := ctVelocity;
364 UpdateAfterChangeTransformation;
365 end;
366
367 procedure TViewPlay.ClickChangeTransformationForce(Sender: TObject);
368 begin
369 {$ifdef CASTLE_UNFINISHED_CHANGE_TRANSFORMATION_BY_FORCE}
370 ThirdPersonNavigation.ChangeTransformation := ctForce;
371 {$endif}
372 UpdateAfterChangeTransformation;
373 end;
374
375 end.