Debian Codegraph @

examples/platformer/code/gameviewplay.pas

raw
1 {
2 Copyright 2021-2024 Andrzej Kilijański, 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 interface
20
21 uses Classes,
22 CastleComponentSerialize, CastleUIControls, CastleControls,
23 CastleKeysMouse, CastleViewport, CastleScene, CastleSceneCore, CastleVectors,
24 CastleTransform, CastleSoundEngine, X3DNodes,
25 GameEnemy, GameFallingObstacle, GameDeadlyObstacle, GameMovingPlatform;
26
27 type
28 TLevelBounds = class (TComponent)
29 public
30 Left: Single;
31 Right: Single;
32 Top: Single;
33 Down: Single;
34 constructor Create(AOwner: TComponent);override;
35 end;
36
37 TBullet = class(TCastleTransform)
38 strict private
39 Duration: Single;
40 FRBody: TCastleRigidBody;
41 public
42 constructor Create(AOwner: TComponent; const BulletSpriteScene: TCastleScene); reintroduce;
43 procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override;
44 { Physics body. Guaranteed to be initialized (non-nil) for TBullet. }
45 property RBody: TCastleRigidBody read FRBody;
46 end;
47
48 { Main "playing game" view, where most of the game logic takes place. }
49 TViewPlay = class(TCastleView)
50 published
51 { Components designed using CGE editor.
52 These fields will be automatically initialized at Start. }
53 LabelFps: TCastleLabel;
54 LabelCollectedCoins: TCastleLabel;
55 MainViewport: TCastleViewport;
56 ScenePlayer: TCastleScene;
57 PlayerRigidBody: TCastleRigidBody;
58 CheckboxCameraFollow: TCastleCheckbox;
59 CheckboxAdvancedPlayer: TCastleCheckbox;
60 ImageHitPoint4: TCastleImageControl;
61 ImageHitPoint3: TCastleImageControl;
62 ImageHitPoint2: TCastleImageControl;
63 ImageHitPoint1: TCastleImageControl;
64 ImageKey: TCastleImageControl;
65 ButtonPause: TCastleButton;
66 strict private
67 { Checks this is first Update when the InputJump occurred.
68 See ../README.md for documentation about allowed keys/mouse/touch input. }
69 WasInputJump: Boolean;
70
71 { Checks this is firs Update when InputShot occurred.
72 See ../README.md for documentation about allowed keys/mouse/touch input. }
73 WasInputShot: Boolean;
74
75 { Player abilities }
76 PlayerCanDoubleJump: Boolean;
77 WasDoubleJump: Boolean;
78 PlayerCanShot: Boolean;
79 PlayerCollectedCoins: Integer;
80 PlayerHitPoints: Integer;
81 PlayerAnimationToLoop: String;
82 PlayerHasKey: Boolean;
83
84 LevelComplete: Boolean;
85
86 BulletSpriteScene: TCastleScene;
87
88 { Level bounds }
89 LevelBounds: TLevelBounds;
90
91 { Enemies behaviors }
92 Enemies: TEnemyList;
93
94 { Falling obstacles (spike) behaviors }
95 FallingObstacles: TFallingObstaclesList;
96
97 { Deadly obstacles (spikes) behaviors }
98 DeadlyObstacles: TDeadlyObstaclesList;
99
100 { List of moving platforms behaviors }
101 MovingPlatforms: TMovingPlatformList;
102
103 { Did we show ViewControlsHelp }
104 ControlsHelpShown: Boolean;
105
106 { ResumeGame from nearest Resume call.
107 Set this to @true when doing PauseGame + Container.PushView
108 to show something that pauses the game. }
109 ResumeGameScheduled: Boolean;
110
111 procedure ConfigurePlayerPhysics(const Player:TCastleScene);
112 procedure ConfigurePlayerAbilities(const Player:TCastleScene);
113 procedure PlayerCollisionEnter(const CollisionDetails: TPhysicsCollisionDetails);
114 procedure PlayerCollisionExit(const CollisionDetails: TPhysicsCollisionDetails);
115 procedure ConfigureBulletSpriteScene;
116
117 { Simplest version }
118 procedure UpdatePlayerSimpleDependOnlyVelocity(const SecondsPassed: Single;
119 var HandleInput: Boolean);
120
121 { More advanced version with ray to check "Are we on ground?" }
122 procedure UpdatePlayerByVelocityAndRay(const SecondsPassed: Single;
123 var HandleInput: Boolean);
124
125 { More advanced version with ray to check "Are we on ground?" and
126 double jump }
127 procedure UpdatePlayerByVelocityAndRayWithDblJump(const SecondsPassed: Single;
128 var HandleInput: Boolean);
129
130 { More advanced version with physics ray to check "Are we on ground?" and
131 double jump }
132 procedure UpdatePlayerByVelocityAndPhysicsRayWithDblJump(const SecondsPassed: Single;
133 var HandleInput: Boolean);
134
135 { More advanced version with physics ray to check "Are we on ground?",
136 double jump, shot and move acceleration frame rate independed }
137 procedure UpdatePlayerByVelocityAndPhysicsRayWithDblJumpShot(const SecondsPassed: Single;
138 var HandleInput: Boolean);
139
140 procedure Shot(BulletOwner: TComponent; const Origin, Direction: TVector3);
141
142 { Coins support }
143 procedure CollectCoin;
144 procedure ResetCollectedCoins;
145
146 { Life support }
147 procedure ResetHitPoints;
148 procedure SetHitPoints(const HitPoints: Integer);
149
150 { Key support }
151 procedure CollectKey;
152 procedure ResetCollectedKeys;
153
154 procedure PlayAnimationOnceAndLoop(Scene: TCastleScene;
155 const AnimationNameToPlayOnce, AnimationNameToLoop: String);
156 procedure OnAnimationStop(const Scene: TCastleSceneCore;
157 const Animation: TTimeSensorNode);
158
159 { Check pressed keys and mouse/touch, to support both keyboard
160 and mouse and touch (on mobile) navigation. }
161 function InputLeft: Boolean;
162 function InputRight: Boolean;
163 function InputJump: Boolean;
164 function InputShot: Boolean;
165
166 procedure ClickPause(Sender: TObject);
167 public
168 constructor Create(AOwner: TComponent); override;
169 procedure Start; override;
170 procedure Stop; override;
171 procedure Resume; override;
172 procedure Update(const SecondsPassed: Single; var HandleInput: Boolean); override;
173 function Press(const Event: TInputPressRelease): Boolean; override;
174
175 { Public functions }
176 procedure HitPlayer;
177 function IsPlayerDead: Boolean;
178
179 procedure PauseGame;
180 procedure ResumeGame;
181 end;
182
183 var
184 ViewPlay: TViewPlay;
185
186 implementation
187
188 uses
189 SysUtils, Math,
190 CastleLog, CastleApplicationProperties,
191 GameSound, GameViewMenu, GameViewGameOver, GameViewLevelComplete, GameViewPause,
192 GameViewControlsHelp;
193
194 { TBullet -------------------------------------------------------------------- }
195
196 constructor TBullet.Create(AOwner: TComponent; const BulletSpriteScene: TCastleScene);
197 var
198 Col: TCastleSphereCollider;
199 begin
200 inherited Create(AOwner);
201
202 Add(BulletSpriteScene);
203 BulletSpriteScene.Visible := true;
204 BulletSpriteScene.Translation := Vector3(0, 0, 0);
205
206 { In this case we are adding TCastleRigidBody to TBullet(TCastleTransform)
207 and not to the BulletSpriteScene in order to be able to use this scene in
208 multiple bullets. }
209 FRBody := TCastleRigidBody.Create(Self);
210 RBody.Setup2D;
211 RBody.Dynamic := true;
212 RBody.CollisionDetection := cdContinuous;
213 RBody.MaxLinearVelocity := 0;
214 RBody.Layer := 3;
215
216 Col := TCastleSphereCollider.Create(Self);
217 { We don't set the Radius becouse we simply use Autosize }
218 // Col.Radius := BulletSpriteScene.BoundingBox.Size.X / 2;
219 { Make bullet more bouncy }
220 Col.Restitution := 0.6;
221 Col.Mass := 1;
222
223 AddBehavior(Col);
224 AddBehavior(RBody);
225 end;
226
227 procedure TBullet.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType
228 );
229 begin
230 inherited Update(SecondsPassed, RemoveMe);
231
232 Duration := Duration + SecondsPassed;
233 if Duration > 3 then
234 RemoveMe := rtRemoveAndFree;
235 end;
236
237 { TLevelBounds --------------------------------------------------------------- }
238
239 constructor TLevelBounds.Create(AOwner: TComponent);
240 begin
241 inherited Create(AOwner);
242 Left := -3072;
243 Right := 5120;
244 Top := 3072;
245 Down := -800;
246 end;
247
248 { TViewPlay ----------------------------------------------------------------- }
249
250 constructor TViewPlay.Create(AOwner: TComponent);
251 begin
252 inherited;
253 DesignUrl := 'castle-data:/gameviewplay.castle-user-interface';
254 end;
255
256 function TViewPlay.InputLeft: Boolean;
257 var
258 I: Integer;
259 begin
260 Result :=
261 Container.Pressed.Items[keyA] or
262 Container.Pressed.Items[keyArrowLeft];
263
264 { Mouse, or any finger, pressing in left-lower part of the screen.
265
266 Note: if we would not need to support multi-touch (and only wanted
267 to check 1st finger) then we would use simpler "Container.MousePosition"
268 instead of "Container.TouchesCount", "Container.Touches[..].Position". }
269
270 if buttonLeft in Container.MousePressed then
271 for I := 0 to Container.TouchesCount - 1 do
272 if (Container.Touches[I].Position.X < Container.PixelsWidth * 0.5) and
273 (Container.Touches[I].Position.Y < Container.PixelsHeight * 0.5) then
274 Exit(true);
275 end;
276
277 function TViewPlay.InputRight: Boolean;
278 var
279 I: Integer;
280 begin
281 Result :=
282 Container.Pressed.Items[keyD] or
283 Container.Pressed.Items[keyArrowRight];
284
285 { Mouse, or any finger, pressing in left-lower part of the screen. }
286 if buttonLeft in Container.MousePressed then
287 for I := 0 to Container.TouchesCount - 1 do
288 if (Container.Touches[I].Position.X >= Container.PixelsWidth * 0.5) and
289 (Container.Touches[I].Position.Y < Container.PixelsHeight * 0.5) then
290 Exit(true);
291 end;
292
293 function TViewPlay.InputJump: Boolean;
294 var
295 I: Integer;
296 begin
297 Result :=
298 Container.Pressed.Items[keyW] or
299 Container.Pressed.Items[keyArrowUp];
300
301 { Mouse, or any finger, pressing in upper part of the screen. }
302 if buttonLeft in Container.MousePressed then
303 for I := 0 to Container.TouchesCount - 1 do
304 if (Container.Touches[I].Position.Y >= Container.PixelsHeight * 0.5) then
305 Exit(true);
306 end;
307
308 function TViewPlay.InputShot: Boolean;
309 begin
310 Result :=
311 Container.Pressed.Items[keySpace] or
312 { Right mouse button, or 2 fingers, are held. }
313 (buttonRight in Container.MousePressed) or
314 (Container.TouchesCount >= 2);
315 end;
316
317 procedure TViewPlay.ConfigurePlayerPhysics(
318 const Player: TCastleScene);
319 var
320 RBody: TCastleRigidBody;
321 begin
322 RBody := Player.FindBehavior(TCastleRigidBody) as TCastleRigidBody;
323 if RBody<> nil then
324 begin
325 RBody.OnCollisionEnter := {$ifdef FPC}@{$endif}PlayerCollisionEnter;
326 RBody.OnCollisionExit := {$ifdef FPC}@{$endif}PlayerCollisionExit;
327 end;
328
329 WasInputJump := false;
330 end;
331
332 procedure TViewPlay.ConfigurePlayerAbilities(const Player: TCastleScene);
333 begin
334 PlayerCanDoubleJump := false;
335 WasDoubleJump := false;
336 PlayerCanShot := false;
337 ResetHitPoints;
338
339 ResetCollectedCoins;
340 ResetCollectedKeys;
341 end;
342
343 procedure TViewPlay.PlayerCollisionEnter(
344 const CollisionDetails: TPhysicsCollisionDetails);
345 begin
346 if CollisionDetails.OtherTransform <> nil then
347 begin
348 if Pos('GoldCoin', CollisionDetails.OtherTransform.Name) > 0 then
349 begin
350 CollectCoin;
351 CollisionDetails.OtherTransform.Exists := false;
352 end else
353 if Pos('DblJump', CollisionDetails.OtherTransform.Name) > 0 then
354 begin
355 SoundEngine.Play(NamedSound('PowerUp'));
356 PlayerCanDoubleJump := true;
357 CollisionDetails.OtherTransform.Exists := false;
358 end else
359 if Pos('Shot', CollisionDetails.OtherTransform.Name) > 0 then
360 begin
361 SoundEngine.Play(NamedSound('PowerUp'));
362 PlayerCanShot := true;
363 CollisionDetails.OtherTransform.Exists := false;
364 end else
365 if Pos('Key', CollisionDetails.OtherTransform.Name) > 0 then
366 begin
367 CollectKey;
368 CollisionDetails.OtherTransform.Exists := false;
369 end else
370 if Pos('Door', CollisionDetails.OtherTransform.Name) > 0 then
371 begin
372 if PlayerHasKey then
373 LevelComplete := true
374 else
375 { Show no key message. }
376 CollisionDetails.OtherTransform.Items[0].Exists := true;
377 end;
378 end;
379 end;
380
381 procedure TViewPlay.PlayerCollisionExit(
382 const CollisionDetails: TPhysicsCollisionDetails);
383 begin
384 { Hide no key message. }
385 if CollisionDetails.OtherTransform <> nil then
386 begin
387 if (Pos('Door', CollisionDetails.OtherTransform.Name) > 0) and
388 (not PlayerHasKey) then
389 CollisionDetails.OtherTransform.Items[0].Exists := false;
390 end;
391 end;
392
393 procedure TViewPlay.ConfigureBulletSpriteScene;
394 begin
395 BulletSpriteScene := TCastleScene.Create(FreeAtStop);
396 BulletSpriteScene.URL := 'castle-data:/bullet/particle_darkGrey.png';
397 BulletSpriteScene.Scale := Vector3(0.5, 0.5, 0.5);
398 end;
399
400 procedure TViewPlay.UpdatePlayerSimpleDependOnlyVelocity(
401 const SecondsPassed: Single; var HandleInput: Boolean);
402 const
403 JumpVelocity = 700;
404 MaxHorizontalVelocity = 350;
405 var
406 DeltaVelocity: TVector3;
407 Vel: TVector3;
408 PlayerOnGround: Boolean;
409 begin
410 { This method is executed every frame.}
411
412 { When player is dead, he can't do anything }
413 if IsPlayerDead then
414 Exit;
415
416 DeltaVelocity := Vector3(0, 0, 0);
417 Vel := PlayerRigidBody.LinearVelocity;
418
419 { This is not ideal you can do another jump when Player is
420 on top of the jump you can make next jump, but can be nice mechanic
421 for someone }
422 PlayerOnGround := (Abs(Vel.Y) < 10);
423
424 if InputJump then
425 begin
426 if (not WasInputJump) and PlayerOnGround then
427 begin
428 DeltaVelocity.Y := JumpVelocity;
429 WasInputJump := true;
430 end;
431 end else
432 WasInputJump := false;
433
434
435 if InputRight and PlayerOnGround then
436 begin
437 DeltaVelocity.x := MaxHorizontalVelocity / 2;
438 end;
439
440 if InputLeft and PlayerOnGround then
441 begin
442 DeltaVelocity.x := - MaxHorizontalVelocity / 2;
443 end;
444
445 if Vel.X + DeltaVelocity.X > 0 then
446 Vel.X := Min(Vel.X + DeltaVelocity.X, MaxHorizontalVelocity)
447 else
448 Vel.X := Max(Vel.X + DeltaVelocity.X, -MaxHorizontalVelocity);
449
450 Vel.Y := Vel.Y + DeltaVelocity.Y;
451 Vel.Z := 0;
452
453 { Stop the player without slipping }
454 if PlayerOnGround and (not InputRight) and (not InputLeft) then
455 Vel.X := 0;
456
457 PlayerRigidBody.LinearVelocity := Vel;
458
459 { Set animation }
460
461 { We get here 20 because vertical velocity calculated by physics engine when
462 player is on platform have no 0 but some small values to up and down sometimes
463 It can fail when the player goes uphill (will set jump animation) or down
464 will set fall animation }
465 if Vel.Y > 20 then
466 ScenePlayer.PlayAnimation('jump', true)
467 else
468 if Vel.Y < -20 then
469 ScenePlayer.PlayAnimation('fall', true)
470 else
471 if Abs(Vel.X) > 1 then
472 begin
473 if ScenePlayer.CurrentAnimation.X3DName <> 'walk' then
474 ScenePlayer.PlayAnimation('walk', true);
475 end
476 else
477 ScenePlayer.PlayAnimation('idle', true);
478
479 if Vel.X < -1 then
480 ScenePlayer.Scale := Vector3(-1, 1, 1)
481 else if Vel.X > 1 then
482 ScenePlayer.Scale := Vector3(1, 1, 1);
483 end;
484
485 procedure TViewPlay.UpdatePlayerByVelocityAndRay(const SecondsPassed: Single;
486 var HandleInput: Boolean);
487 const
488 JumpVelocity = 700;
489 MaxHorizontalVelocity = 350;
490 var
491 DeltaVelocity: TVector3;
492 Vel: TVector3;
493 PlayerOnGround: Boolean;
494 GroundHit: TPhysicsRayCastResult;
495 begin
496 { This method is executed every frame.}
497
498 { When player is dead, he can't do anything }
499 if IsPlayerDead then
500 Exit;
501
502 DeltaVelocity := Vector3(0, 0, 0);
503 Vel := PlayerRigidBody.LinearVelocity;
504
505 { Check player is on ground }
506 GroundHit := PlayerRigidBody.PhysicsRayCast(ScenePlayer.Translation + Vector3(0, -ScenePlayer.BoundingBox.SizeY / 2, 0), Vector3(0, -1, 0));
507 if GroundHit.Hit then
508 begin
509 // WriteLnLog('Distance ', FloatToStr(Distance));
510 PlayerOnGround := GroundHit.Distance < 2;
511 end else
512 PlayerOnGround := false;
513
514 { Two more checks using physics engine - player should slide down when player is just
515 on the edge.
516 TODO: maybe we can remove this logic after using TCastleCapsule collider for player. }
517 if not PlayerOnGround then
518 begin
519 GroundHit := PlayerRigidBody.PhysicsRayCast(ScenePlayer.Translation + Vector3(-ScenePlayer.BoundingBox.SizeX * 0.30, -ScenePlayer.BoundingBox.SizeY / 2, 0), Vector3(0, -1, 0));
520 if GroundHit.Hit then
521 begin
522 // WriteLnLog('Distance ', FloatToStr(Distance));
523 PlayerOnGround := GroundHit.Distance < 2;
524 end else
525 PlayerOnGround := false;
526 end;
527
528 if not PlayerOnGround then
529 begin
530 GroundHit := PlayerRigidBody.PhysicsRayCast(ScenePlayer.Translation + Vector3(ScenePlayer.BoundingBox.SizeX * 0.30, -ScenePlayer.BoundingBox.SizeY / 2, 0), Vector3(0, -1, 0));
531 if GroundHit.Hit then
532 begin
533 // WriteLnLog('Distance ', FloatToStr(Distance));
534 PlayerOnGround := GroundHit.Distance < 2;
535 end else
536 PlayerOnGround := false;
537 end;
538
539 if InputJump then
540 begin
541 if (not WasInputJump) and PlayerOnGround then
542 begin
543 DeltaVelocity.Y := JumpVelocity;
544 WasInputJump := true;
545 end;
546 end else
547 WasInputJump := false;
548
549
550 if InputRight and PlayerOnGround then
551 begin
552 DeltaVelocity.x := MaxHorizontalVelocity / 2;
553 end;
554
555 if InputLeft and PlayerOnGround then
556 begin
557 DeltaVelocity.x := - MaxHorizontalVelocity / 2;
558 end;
559
560 if Vel.X + DeltaVelocity.X > 0 then
561 Vel.X := Min(Vel.X + DeltaVelocity.X, MaxHorizontalVelocity)
562 else
563 Vel.X := Max(Vel.X + DeltaVelocity.X, -MaxHorizontalVelocity);
564
565 Vel.Y := Vel.Y + DeltaVelocity.Y;
566 Vel.Z := 0;
567
568 { Stop the player without slipping }
569 if PlayerOnGround and (not InputRight) and (not InputLeft) then
570 Vel.X := 0;
571
572 PlayerRigidBody.LinearVelocity := Vel;
573
574 { Set animation }
575
576 { We get here 20 because vertical velocity calculated by physics engine when
577 player is on platform have no 0 but some small values to up and down sometimes
578 It can fail when the player goes uphill (will set jump animation) or down
579 will set fall animation }
580 if Vel.Y > 20 then
581 ScenePlayer.PlayAnimation('jump', true)
582 else
583 if Vel.Y < -20 then
584 ScenePlayer.PlayAnimation('fall', true)
585 else
586 if Abs(Vel.X) > 1 then
587 begin
588 if ScenePlayer.CurrentAnimation.X3DName <> 'walk' then
589 ScenePlayer.PlayAnimation('walk', true);
590 end
591 else
592 ScenePlayer.PlayAnimation('idle', true);
593
594 if Vel.X < -1 then
595 ScenePlayer.Scale := Vector3(-1, 1, 1)
596 else if Vel.X > 1 then
597 ScenePlayer.Scale := Vector3(1, 1, 1);
598 end;
599
600 procedure TViewPlay.UpdatePlayerByVelocityAndRayWithDblJump(
601 const SecondsPassed: Single; var HandleInput: Boolean);
602 const
603 JumpVelocity = 700;
604 MaxHorizontalVelocity = 350;
605 var
606 DeltaVelocity: TVector3;
607 Vel: TVector3;
608 PlayerOnGround: Boolean;
609 GroundHit: TPhysicsRayCastResult;
610 InSecondJump: Boolean;
611 begin
612 { This method is executed every frame.}
613
614 { When player is dead, he can't do anything }
615 if IsPlayerDead then
616 Exit;
617
618 InSecondJump := false;
619
620 DeltaVelocity := Vector3(0, 0, 0);
621 Vel := PlayerRigidBody.LinearVelocity;
622
623 { Check player is on ground }
624 GroundHit := PlayerRigidBody.PhysicsRayCast(ScenePlayer.Translation + Vector3(0, -ScenePlayer.BoundingBox.SizeY / 2, 0), Vector3(0, -1, 0));
625 if GroundHit.Hit then
626 begin
627 // WriteLnLog('Distance ', FloatToStr(Distance));
628 PlayerOnGround := GroundHit.Distance < 2;
629 end else
630 PlayerOnGround := false;
631
632 { Two more checks using physics - player should slide down when player just
633 on the edge, maye be can remove that when add Capsule collider }
634 if not PlayerOnGround then
635 begin
636 GroundHit := PlayerRigidBody.PhysicsRayCast(ScenePlayer.Translation + Vector3(-ScenePlayer.BoundingBox.SizeX * 0.30 , -ScenePlayer.BoundingBox.SizeY / 2, 0), Vector3(0, -1, 0));
637 if GroundHit.Hit then
638 begin
639 // WriteLnLog('Distance ', FloatToStr(Distance));
640 PlayerOnGround := GroundHit.Distance < 2;
641 end else
642 PlayerOnGround := false;
643 end;
644
645 if not PlayerOnGround then
646 begin
647 GroundHit := PlayerRigidBody.PhysicsRayCast(ScenePlayer.Translation + Vector3(ScenePlayer.BoundingBox.SizeX * 0.30, -ScenePlayer.BoundingBox.SizeY / 2, 0), Vector3(0, -1, 0));
648 if GroundHit.Hit then
649 begin
650 // WriteLnLog('Distance ', FloatToStr(Distance));
651 PlayerOnGround := GroundHit.Distance < 2;
652 end else
653 PlayerOnGround := false;
654 end;
655
656 if PlayerOnGround then
657 WasDoubleJump := false;
658
659 if InputJump then
660 begin
661 if (not WasInputJump) and (PlayerOnGround or (PlayerCanDoubleJump and (not WasDoubleJump))) then
662 begin
663 if not PlayerOnGround then
664 begin
665 WasDoubleJump := true;
666 InSecondJump := true;
667 { In second jump just add diffrence betwen current Velocity and JumpVelocity }
668 DeltaVelocity.Y := JumpVelocity - Vel.Y;
669 end else
670 DeltaVelocity.Y := JumpVelocity;
671 WasInputJump := true;
672 end;
673 end else
674 WasInputJump := false;
675
676 if InputRight then
677 begin
678 if PlayerOnGround then
679 DeltaVelocity.x := MaxHorizontalVelocity / 2
680 else if InSecondJump then
681 { When key is pressed when you make second jump you can increase
682 horizontal speed }
683 DeltaVelocity.x := MaxHorizontalVelocity / 3
684 else
685 { This add a little control when you in the air during jumping or falling }
686 DeltaVelocity.x := MaxHorizontalVelocity / 20;
687 end;
688
689 if InputLeft then
690 begin
691 if PlayerOnGround then
692 DeltaVelocity.x := - MaxHorizontalVelocity / 2
693 else if InSecondJump then
694 { When key is pressed when you make second jump you can increase
695 horizontal speed }
696 DeltaVelocity.x := - MaxHorizontalVelocity / 3
697 else
698 { This add a little control when you in the air during jumping or falling }
699 DeltaVelocity.x := - MaxHorizontalVelocity / 20;
700 end;
701
702 if Vel.X + DeltaVelocity.X > 0 then
703 Vel.X := Min(Vel.X + DeltaVelocity.X, MaxHorizontalVelocity)
704 else
705 Vel.X := Max(Vel.X + DeltaVelocity.X, -MaxHorizontalVelocity);
706
707 Vel.Y := Vel.Y + DeltaVelocity.Y;
708 Vel.Z := 0;
709
710 { Stop the player without slipping }
711 if PlayerOnGround and (not InputRight) and (not InputLeft) then
712 Vel.X := 0;
713
714 PlayerRigidBody.LinearVelocity := Vel;
715
716 { Set animation }
717
718 { We get here 20 because vertical velocity calculated by physics engine when
719 player is on platform have no 0 but some small values to up and down sometimes
720 It can fail when the player goes uphill (will set jump animation) or down
721 will set fall animation }
722 if (not PlayerOnGround) and (Vel.Y > 20) then
723 ScenePlayer.PlayAnimation('jump', true)
724 else
725 if (not PlayerOnGround) and (Vel.Y < -20) then
726 ScenePlayer.PlayAnimation('fall', true)
727 else
728 if Abs(Vel.X) > 1 then
729 begin
730 if ScenePlayer.CurrentAnimation.X3DName <> 'walk' then
731 ScenePlayer.PlayAnimation('walk', true);
732 end
733 else
734 ScenePlayer.PlayAnimation('idle', true);
735
736 if Vel.X < -1 then
737 ScenePlayer.Scale := Vector3(-1, 1, 1)
738 else if Vel.X > 1 then
739 ScenePlayer.Scale := Vector3(1, 1, 1);
740 end;
741
742 procedure TViewPlay.UpdatePlayerByVelocityAndPhysicsRayWithDblJump(
743 const SecondsPassed: Single; var HandleInput: Boolean);
744 const
745 JumpVelocity = 700;
746 MaxHorizontalVelocity = 350;
747 AirControlFactor = 20;
748 var
749 DeltaVelocity: TVector3;
750 Vel: TVector3;
751 PlayerOnGround: Boolean;
752 InSecondJump: Boolean;
753 begin
754 { This method is executed every frame.}
755
756 { When player is dead, he can't do anything }
757 if IsPlayerDead then
758 Exit;
759
760 InSecondJump := false;
761
762 DeltaVelocity := Vector3(0, 0, 0);
763 Vel := PlayerRigidBody.LinearVelocity;
764
765 { Check player is on ground }
766 PlayerOnGround := PlayerRigidBody.PhysicsRayCast(ScenePlayer.Translation,
767 Vector3(0, -1, 0), ScenePlayer.BoundingBox.SizeY / 2 + 5).Hit;
768
769 { Two more checks using physics - player should slide down when player just
770 on the edge, but sometimes it stay and center ray dont "see" that we are
771 on ground }
772 if not PlayerOnGround then
773 begin
774 PlayerOnGround := PlayerRigidBody.PhysicsRayCast(ScenePlayer.Translation
775 + Vector3(-ScenePlayer.BoundingBox.SizeX * 0.30, 0, 0),
776 Vector3(0, -1, 0), ScenePlayer.BoundingBox.SizeY / 2 + 5).Hit;
777 end;
778
779 if not PlayerOnGround then
780 begin
781 PlayerOnGround := PlayerRigidBody.PhysicsRayCast(ScenePlayer.Translation
782 + Vector3(ScenePlayer.BoundingBox.SizeX * 0.30, 0, 0),
783 Vector3(0, -1, 0), ScenePlayer.BoundingBox.SizeY / 2 + 5).Hit;
784 end;
785
786 if PlayerOnGround then
787 WasDoubleJump := false;
788
789 if InputJump then
790 begin
791 if (not WasInputJump) and (PlayerOnGround or (PlayerCanDoubleJump and (not WasDoubleJump))) then
792 begin
793 if not PlayerOnGround then
794 begin
795 WasDoubleJump := true;
796 InSecondJump := true;
797 { In second jump just add diffrence betwen current Velocity and JumpVelocity }
798 DeltaVelocity.Y := JumpVelocity - Vel.Y;
799 end else
800 DeltaVelocity.Y := JumpVelocity;
801 WasInputJump := true;
802 end;
803 end else
804 WasInputJump := false;
805
806 if InputRight then
807 begin
808 if PlayerOnGround then
809 DeltaVelocity.x := MaxHorizontalVelocity / 2
810 else if InSecondJump then
811 { When key is pressed when you make second jump you can increase
812 horizontal speed }
813 DeltaVelocity.x := MaxHorizontalVelocity / 3
814 else
815 { This add a little control when you in the air during jumping or falling }
816 DeltaVelocity.x := MaxHorizontalVelocity / 20;
817 end;
818
819 if InputLeft then
820 begin
821 if PlayerOnGround then
822 DeltaVelocity.x := - MaxHorizontalVelocity / 2
823 else if InSecondJump then
824 { When key is pressed when you make second jump you can increase
825 horizontal speed }
826 DeltaVelocity.x := - MaxHorizontalVelocity / 3
827 else
828 { This add a little control when you in the air during jumping or falling }
829 DeltaVelocity.x := - MaxHorizontalVelocity / 20;
830 end;
831
832 if Vel.X + DeltaVelocity.X > 0 then
833 Vel.X := Min(Vel.X + DeltaVelocity.X, MaxHorizontalVelocity)
834 else
835 Vel.X := Max(Vel.X + DeltaVelocity.X, -MaxHorizontalVelocity);
836
837 Vel.Y := Vel.Y + DeltaVelocity.Y;
838 Vel.Z := 0;
839
840 { Stop the player without slipping }
841 if PlayerOnGround and (not InputRight) and (not InputLeft) then
842 Vel.X := 0;
843
844 PlayerRigidBody.LinearVelocity := Vel;
845
846 { Set animation }
847
848 { We get here 20 because vertical velocity calculated by physics engine when
849 player is on platform have no 0 but some small values to up and down sometimes
850 It can fail when the player goes uphill (will set jump animation) or down
851 will set fall animation }
852 if (not PlayerOnGround) and (Vel.Y > 20) then
853 ScenePlayer.PlayAnimation('jump', true)
854 else
855 if (not PlayerOnGround) and (Vel.Y < -20) then
856 ScenePlayer.PlayAnimation('fall', true)
857 else
858 if Abs(Vel.X) > 1 then
859 begin
860 if ScenePlayer.CurrentAnimation.X3DName <> 'walk' then
861 ScenePlayer.PlayAnimation('walk', true);
862 end
863 else
864 ScenePlayer.PlayAnimation('idle', true);
865
866 if Vel.X < -1 then
867 ScenePlayer.Scale := Vector3(-1, 1, 1)
868 else if Vel.X > 1 then
869 ScenePlayer.Scale := Vector3(1, 1, 1);
870 end;
871
872 procedure TViewPlay.UpdatePlayerByVelocityAndPhysicsRayWithDblJumpShot(
873 const SecondsPassed: Single; var HandleInput: Boolean);
874 const
875 JumpVelocity = 680;
876 MaxHorizontalVelocity = 345;
877 { We need multiply any horizontal velocity speed by SecondsPassed.
878 Without that when game will run 120 FPS, player will accelerated
879 twice faster than on 60 FPS.
880 So MaxHorizontalVelocityChange is designed and tested on 60 FPS so we need
881 multiply MaxHorizontalVelocity by 60 to get it.
882
883 It's easy to realize when you know that for 60 FPS:
884
885 MaxHorizontalVelocityChange * SecondsPassed * 60 = 350
886 21000 * (1/60) * 60 = 350
887 21000 * 0.01666 * 60 = 350
888
889 And for 120 FPS:
890 21000 * (1/120) * 60 = 175
891 21000 * 0.008333 * 60 = 175
892 For 120 FPS every frame max speed up will be 175 but you have two times
893 more frames (updates). So 175 * 2 = 350 like in 60 FPS.
894
895 We don't need that for jump because jump is one time event not changed
896 per update. If something depend from update call frequency you need make it
897 depend from time passed in CGE SecondsPassed.
898 }
899 MaxHorizontalVelocityChange = MaxHorizontalVelocity * 60;
900 var
901 DeltaVelocity: TVector3;
902 Vel: TVector3;
903 PlayerOnGround: Boolean;
904 InSecondJump: Boolean;
905 GroundScene: TCastleTransform;
906 begin
907 { This method is executed every frame.}
908
909 { When player is dead, he can't do anything }
910 if IsPlayerDead then
911 Exit;
912
913 if PlayerRigidBody = nil then
914 Exit;
915
916 DeltaVelocity := Vector3(0, 0, 0);
917 Vel := PlayerRigidBody.LinearVelocity;
918
919 { Check player is on ground }
920 GroundScene := PlayerRigidBody.PhysicsRayCast(ScenePlayer.Translation,
921 Vector3(0, -1, 0), ScenePlayer.BoundingBox.SizeY / 2 + 5).Transform;
922
923 { Two more checks - player should slide down when player just
924 on the edge, but sometimes it stay and center ray don't "see" that we are
925 on ground }
926 if GroundScene = nil then
927 begin
928 GroundScene := PlayerRigidBody.PhysicsRayCast(ScenePlayer.Translation
929 + Vector3(-ScenePlayer.BoundingBox.SizeX * 0.30, 0, 0),
930 Vector3(0, -1, 0), ScenePlayer.BoundingBox.SizeY / 2 + 5).Transform;
931 end;
932
933 if GroundScene = nil then
934 begin
935 GroundScene := PlayerRigidBody.PhysicsRayCast(ScenePlayer.Translation
936 + Vector3(ScenePlayer.BoundingBox.SizeX * 0.30, 0, 0),
937 Vector3(0, -1, 0), ScenePlayer.BoundingBox.SizeY / 2 + 5).Transform;
938 end;
939
940 { Player is on ground when RayCasts hits something }
941 PlayerOnGround := (GroundScene <> nil);
942
943 { Reset DoubleJump flag when player is on ground. }
944 if PlayerOnGround then
945 WasDoubleJump := false;
946
947 { Flag for velocity calculation when second jump starts in this Update }
948 InSecondJump := false;
949 if InputJump then
950 begin
951 { Player can jump when:
952 - is on ground
953 - he can double jump and there was not WasDoubleJump
954 - here we also check if the key has just been pressed (when it is held,
955 the player should not keep jumping) }
956 if (not WasInputJump) and (PlayerOnGround or (PlayerCanDoubleJump and (not WasDoubleJump))) then
957 begin
958 SoundEngine.Play(NamedSound('Jump'));
959 if not PlayerOnGround then
960 begin
961 WasDoubleJump := true;
962 InSecondJump := true;
963 { In second jump just add diffrence between current Velocity and JumpVelocity }
964 DeltaVelocity.Y := JumpVelocity - Vel.Y;
965 end else
966 DeltaVelocity.Y := JumpVelocity;
967 WasInputJump := true;
968 end;
969 end else
970 WasInputJump := false;
971
972 if InputRight then
973 begin
974 if PlayerOnGround then
975 DeltaVelocity.x := MaxHorizontalVelocityChange * SecondsPassed / 2
976 else if InSecondJump then
977 { When key is pressed when you make second jump you can increase
978 horizontal speed }
979 DeltaVelocity.x := MaxHorizontalVelocityChange * SecondsPassed / 3
980 else
981 { This add a little control when you in the air during jumping or falling }
982 DeltaVelocity.x := MaxHorizontalVelocityChange * SecondsPassed / 14;
983 end;
984
985 if InputLeft then
986 begin
987 if PlayerOnGround then
988 DeltaVelocity.x := - MaxHorizontalVelocityChange * SecondsPassed / 2
989 else if InSecondJump then
990 { When key is pressed when you make second jump you can increase
991 horizontal speed }
992 DeltaVelocity.x := - MaxHorizontalVelocityChange * SecondsPassed / 3
993 else
994 { This add a little control when you in the air during jumping or falling }
995 DeltaVelocity.x := - MaxHorizontalVelocityChange * SecondsPassed / 14;
996 end;
997
998 if Vel.X + DeltaVelocity.X > 0 then
999 Vel.X := Min(Vel.X + DeltaVelocity.X, MaxHorizontalVelocity)
1000 else
1001 Vel.X := Max(Vel.X + DeltaVelocity.X, -MaxHorizontalVelocity);
1002
1003 Vel.Y := Vel.Y + DeltaVelocity.Y;
1004 Vel.Z := 0;
1005
1006 { Stop the player without slipping }
1007 if PlayerOnGround and (not InputRight) and (not InputLeft) then
1008 Vel.X := 0;
1009
1010 { Player can't move when hurt on ground }
1011 if PlayerOnGround and (ScenePlayer.CurrentAnimation.X3DName = 'hurt') then
1012 begin
1013 Vel.X := 0;
1014 Vel.Y := 0;
1015 end;
1016
1017 PlayerRigidBody.LinearVelocity := Vel;
1018
1019 { Set animation }
1020
1021 { Don't change animation when player are hurt }
1022 if ScenePlayer.CurrentAnimation.X3DName <> 'hurt' then
1023 begin
1024 { We get here 20 because vertical velocity calculated by physics engine when
1025 player is on platform have no 0 but some small values to up and down sometimes
1026 It can fail when the player goes uphill (will set jump animation) or down
1027 will set fall animation }
1028 if (not PlayerOnGround) and (Vel.Y > 20) then
1029 ScenePlayer.PlayAnimation('jump', true)
1030 else
1031 if (not PlayerOnGround) and (Vel.Y < -20) then
1032 ScenePlayer.PlayAnimation('fall', true)
1033 else
1034 if Abs(Vel.X) > 1 then
1035 begin
1036 if ScenePlayer.CurrentAnimation.X3DName <> 'walk' then
1037 ScenePlayer.PlayAnimation('walk', true);
1038 end
1039 else
1040 ScenePlayer.PlayAnimation('idle', true);
1041 end;
1042
1043 { Here we use horizontal velocity to change player scene direction to moving
1044 direction. }
1045 if Vel.X < -1 then
1046 ScenePlayer.Scale := Vector3(-1, 1, 1)
1047 else if Vel.X > 1 then
1048 ScenePlayer.Scale := Vector3(1, 1, 1);
1049
1050 if PlayerCanShot then
1051 begin
1052 if InputShot then
1053 begin
1054 if WasInputShot = false then
1055 begin
1056 SoundEngine.Play(NamedSound('Shot'));
1057 WasInputShot := true;
1058
1059 Shot(ScenePlayer, ScenePlayer.LocalToWorld(Vector3(ScenePLayer.BoundingBox.SizeX / 2 + 5, 0, 0)),
1060 Vector3(ScenePlayer.Scale.X, 1, 0));
1061 end;
1062 end else
1063 WasInputShot := false;
1064 end;
1065 end;
1066
1067 procedure TViewPlay.Shot(BulletOwner: TComponent; const Origin,
1068 Direction: TVector3);
1069 var
1070 Bullet: TBullet;
1071 begin
1072 Bullet := TBullet.Create(BulletOwner, BulletSpriteScene);
1073 Bullet.Translation := Origin;
1074 Bullet.RBody.LinearVelocity := Direction * Vector3(750, 20, 0);
1075 MainViewport.Items.Add(Bullet);
1076 end;
1077
1078 procedure TViewPlay.CollectCoin;
1079 begin
1080 SoundEngine.Play(NamedSound('Coin'));
1081 Inc(PlayerCollectedCoins);
1082 LabelCollectedCoins.Caption := PlayerCollectedCoins.ToString;
1083 end;
1084
1085 procedure TViewPlay.ResetCollectedCoins;
1086 begin
1087 PlayerCollectedCoins := 0;
1088 LabelCollectedCoins.Caption := '0';
1089 end;
1090
1091 procedure TViewPlay.HitPlayer;
1092 begin
1093 SetHitPoints(PlayerHitPoints - 1);
1094 SoundEngine.Play(NamedSound('Hurt'));
1095 PlayAnimationOnceAndLoop(ScenePlayer, 'hurt', 'idle');
1096 end;
1097
1098 function TViewPlay.IsPlayerDead: Boolean;
1099 begin
1100 Result := PlayerHitPoints < 0;
1101 end;
1102
1103 procedure TViewPlay.PauseGame;
1104 begin
1105 MainViewport.Items.TimeScale := 0;
1106 end;
1107
1108 procedure TViewPlay.ResumeGame;
1109 begin
1110 MainViewport.Items.TimeScale := 1;
1111 end;
1112
1113 procedure TViewPlay.ResetHitPoints;
1114 begin
1115 SetHitPoints(4);
1116 end;
1117
1118 procedure TViewPlay.SetHitPoints(const HitPoints: Integer);
1119 begin
1120 PlayerHitPoints := HitPoints;
1121
1122 if PlayerHitPoints > 3 then
1123 ImageHitPoint4.URL := 'castle-data:/ui/hud_heartFull.png'
1124 else
1125 ImageHitPoint4.URL := 'castle-data:/ui/hud_heartEmpty.png';
1126
1127 if PlayerHitPoints > 2 then
1128 ImageHitPoint3.URL := 'castle-data:/ui/hud_heartFull.png'
1129 else
1130 ImageHitPoint3.URL := 'castle-data:/ui/hud_heartEmpty.png';
1131
1132 if PlayerHitPoints > 1 then
1133 ImageHitPoint2.URL := 'castle-data:/ui/hud_heartFull.png'
1134 else
1135 ImageHitPoint2.URL := 'castle-data:/ui/hud_heartEmpty.png';
1136
1137 if PlayerHitPoints > 0 then
1138 ImageHitPoint1.URL := 'castle-data:/ui/hud_heartFull.png'
1139 else
1140 ImageHitPoint1.URL := 'castle-data:/ui/hud_heartEmpty.png';
1141 end;
1142
1143 procedure TViewPlay.CollectKey;
1144 begin
1145 SoundEngine.Play(NamedSound('PowerUp'));
1146 PlayerHasKey := true;
1147 ImageKey.Exists := true;
1148 end;
1149
1150 procedure TViewPlay.ResetCollectedKeys;
1151 begin
1152 PlayerHasKey := false;
1153 ImageKey.Exists := false;
1154 end;
1155
1156 procedure TViewPlay.PlayAnimationOnceAndLoop(Scene: TCastleScene;
1157 const AnimationNameToPlayOnce, AnimationNameToLoop: String);
1158 var
1159 Parameters: TPlayAnimationParameters;
1160 begin
1161 Parameters := TPlayAnimationParameters.Create;
1162 try
1163 Parameters.Loop := false;
1164 Parameters.Name := AnimationNameToPlayOnce;
1165 Parameters.Forward := true;
1166 Parameters.StopNotification := {$ifdef FPC}@{$endif}OnAnimationStop;
1167 PlayerAnimationToLoop := AnimationNameToLoop;
1168 Scene.PlayAnimation(Parameters);
1169 finally
1170 FreeAndNil(Parameters);
1171 end;
1172 end;
1173
1174 procedure TViewPlay.OnAnimationStop(const Scene: TCastleSceneCore;
1175 const Animation: TTimeSensorNode);
1176 begin
1177 Scene.PlayAnimation(PlayerAnimationToLoop, true);
1178 end;
1179
1180 procedure TViewPlay.Start;
1181 var
1182 { TCastleTransforms that groups objects in our level }
1183 PlatformsRoot: TCastleTransform;
1184 EnemiesRoot: TCastleTransform;
1185 FallingObstaclesRoot: TCastleTransform;
1186 DeadlyObstaclesRoot: TCastleTransform;
1187
1188 { Variables used when interating each object groups }
1189 PlatformScene: TCastleScene;
1190 EnemyScene: TCastleScene;
1191 FallingObstacleScene: TCastleScene;
1192 DeadlyObstacleScene: TCastleScene;
1193
1194 { Variables used to create behaviors }
1195 Enemy: TEnemy;
1196 FallingObstacle: TFallingObstacle;
1197 DeadlyObstacle: TDeadlyObstacle;
1198 MovingPlatform: TMovingPlatform;
1199
1200 I: Integer;
1201 begin
1202 inherited;
1203
1204 {ScenePlayer.World.PhysicsProperties.LayerCollisons.Collides[0,1] := true; // ground collide with player
1205 ScenePlayer.World.PhysicsProperties.LayerCollisons.Collides[0,0] := true; // ground collide with ground
1206 ScenePlayer.World.PhysicsProperties.LayerCollisons.Collides[0,2] := true; // ground collide with enemies
1207
1208 ScenePlayer.World.PhysicsProperties.LayerCollisons.Collides[1,1] := false; // player don't collide with player
1209 ScenePlayer.World.PhysicsProperties.LayerCollisons.Collides[1,2] := true; // player collide with enemies
1210 ScenePlayer.World.PhysicsProperties.LayerCollisons.Collides[1,0] := true; // player collide with ground
1211
1212 ScenePlayer.World.PhysicsProperties.LayerCollisons.Collides[2,0] := true; // enemies collide with ground
1213 ScenePlayer.World.PhysicsProperties.LayerCollisons.Collides[2,1] := true; // enemies collide with player
1214 ScenePlayer.World.PhysicsProperties.LayerCollisons.Collides[2,2] := false; // enemies don't collide with each other
1215
1216 ScenePlayer.RigidBody.Layer := 1;}
1217
1218 LevelComplete := false;
1219
1220 LevelBounds := TLevelBounds.Create(ScenePlayer.Owner);
1221
1222 WasInputShot := false;
1223
1224 { Configure physics and behaviors for platforms }
1225 MovingPlatforms := TMovingPlatformList.Create(true);
1226 PlatformsRoot := DesignedComponent('Platforms') as TCastleTransform;
1227 for I := 0 to PlatformsRoot.Count - 1 do
1228 begin
1229 PlatformScene := PlatformsRoot.Items[I] as TCastleScene;
1230 WritelnLog('Configure platform: ' + PlatformScene.Name);
1231
1232 { We use Tag to set distance for moving platform, so when its other than 0
1233 we need add behavior to it. }
1234 if PlatformScene.Tag <> 0 then
1235 begin
1236 MovingPlatform := TMovingPlatform.Create(nil);
1237 PlatformScene.AddBehavior(MovingPlatform);
1238 MovingPlatforms.Add(MovingPlatform);
1239 end;
1240 end;
1241
1242 Enemies := TEnemyList.Create(true);
1243 EnemiesRoot := DesignedComponent('Enemies') as TCastleTransform;
1244 for I := 0 to EnemiesRoot.Count - 1 do
1245 begin
1246 EnemyScene := EnemiesRoot.Items[I] as TCastleScene;
1247 {EnemyScene.RigidBody.Layer := 2;}
1248
1249 if not EnemyScene.Exists then
1250 Continue;
1251
1252 { Below using nil as Owner of TEnemy, as the Enemies list already "owns"
1253 instances of this class, i.e. it will free them. }
1254 Enemy := TEnemy.Create(nil);
1255 EnemyScene.AddBehavior(Enemy);
1256 Enemies.Add(Enemy);
1257 end;
1258
1259 FallingObstacles := TFallingObstaclesList.Create(true);
1260 FallingObstaclesRoot := DesignedComponent('FallingObstacles') as TCastleTransform;
1261 for I := 0 to FallingObstaclesRoot.Count - 1 do
1262 begin
1263 FallingObstacleScene := FallingObstaclesRoot.Items[I] as TCastleScene;
1264 { Below using nil as Owner of TFallingObstacle,
1265 as the FallingObstacles list already "owns" instances of this class,
1266 i.e. it will free them. }
1267 FallingObstacle := TFallingObstacle.Create(nil);
1268 FallingObstacleScene.AddBehavior(FallingObstacle);
1269 FallingObstacles.Add(FallingObstacle);
1270 end;
1271
1272 DeadlyObstacles := TDeadlyObstaclesList.Create(true);
1273 DeadlyObstaclesRoot := DesignedComponent('DeadlyObstacles') as TCastleTransform;
1274 for I := 0 to DeadlyObstaclesRoot.Count - 1 do
1275 begin
1276 DeadlyObstacleScene := DeadlyObstaclesRoot.Items[I] as TCastleScene;
1277 { Below using nil as Owner of TFallingObstacle,
1278 as the DeadlyObstacles list already "owns" instances of this class,
1279 i.e. it will free them. }
1280 DeadlyObstacle := TDeadlyObstacle.Create(nil);
1281 DeadlyObstacleScene.AddBehavior(DeadlyObstacle);
1282 DeadlyObstacles.Add(DeadlyObstacle);
1283 end;
1284
1285 { Configure physics for player - done in editor, only event in code }
1286 ConfigurePlayerPhysics(ScenePlayer);
1287
1288 ConfigurePlayerAbilities(ScenePlayer);
1289
1290 ConfigureBulletSpriteScene;
1291
1292 { Play game music }
1293 SoundEngine.LoopingChannel[0].Sound := NamedSound('GameMusic');
1294
1295 { ButtonPause is necessary to be able to enter pause on mobile,
1296 where Escape key is not available. }
1297 ButtonPause.Exists := ApplicationProperties.TouchDevice;
1298 ButtonPause.OnClick := {$ifdef FPC}@{$endif} ClickPause;
1299
1300 WritelnLog('Configuration done');
1301 end;
1302
1303 procedure TViewPlay.Stop;
1304 begin
1305 FreeAndNil(Enemies);
1306 FreeAndNil(FallingObstacles);
1307 FreeAndNil(DeadlyObstacles);
1308 FreeAndNil(MovingPlatforms);
1309 inherited;
1310 end;
1311
1312 procedure TViewPlay.Resume;
1313 begin
1314 inherited Resume;
1315
1316 { Play game music }
1317 SoundEngine.LoopingChannel[0].Sound := NamedSound('GameMusic');
1318
1319 if ResumeGameScheduled then
1320 begin
1321 ResumeGame;
1322 ResumeGameScheduled := false;
1323 end;
1324 end;
1325
1326 procedure TViewPlay.Update(const SecondsPassed: Single; var HandleInput: Boolean);
1327 var
1328 CamPos: TVector3;
1329 ViewHeight: Single;
1330 ViewWidth: Single;
1331 begin
1332 inherited;
1333 { This virtual method is executed every frame (many times per second). }
1334
1335 { Show controls help on mobile, once, when game starts }
1336 if (not ControlsHelpShown) and
1337 ApplicationProperties.TouchDevice and
1338 (Container.FrontView = Self) then
1339 begin
1340 ControlsHelpShown := true;
1341 PauseGame;
1342 ResumeGameScheduled := true;
1343 Container.PushView(ViewControlsHelp);
1344 Exit;
1345 end;
1346
1347 { If player is dead and we did not show game over view we do that }
1348 if IsPlayerDead and (Container.FrontView <> ViewGameOver) then
1349 begin
1350 ScenePlayer.Exists := false;
1351 Container.PushView(ViewGameOver);
1352 Exit;
1353 end;
1354
1355 { If level is completed and we did not show level complete we do that }
1356 if LevelComplete and (Container.FrontView <> ViewLevelComplete) then
1357 begin
1358 PlayerRigidBody.Exists := false;
1359 PauseGame;
1360 Container.PushView(ViewLevelComplete);
1361 Exit;
1362 end;
1363
1364 LabelFps.Caption := 'FPS: ' + Container.Fps.ToString;
1365
1366 if CheckboxCameraFollow.Checked then
1367 begin
1368 ViewHeight := MainViewport.Camera.Orthographic.EffectiveRect.Height;
1369 ViewWidth := MainViewport.Camera.Orthographic.EffectiveRect.Width;
1370
1371 CamPos := MainViewport.Camera.Translation;
1372 CamPos.X := ScenePlayer.Translation.X;
1373 CamPos.Y := ScenePlayer.Translation.Y;
1374
1375 { Camera always stay on level }
1376 if CamPos.Y - ViewHeight / 2 < LevelBounds.Down then
1377 CamPos.Y := LevelBounds.Down + ViewHeight / 2;
1378
1379 if CamPos.Y + ViewHeight / 2 > LevelBounds.Top then
1380 CamPos.Y := LevelBounds.Top - ViewHeight / 2;
1381
1382 if CamPos.X - ViewWidth / 2 < LevelBounds.Left then
1383 CamPos.X := LevelBounds.Left + ViewWidth / 2;
1384
1385 if CamPos.X + ViewWidth / 2 > LevelBounds.Right then
1386 CamPos.X := LevelBounds.Right - ViewWidth / 2;
1387
1388 MainViewport.Camera.Translation := CamPos;
1389 end;
1390
1391 if Container.FrontView = Self then // do not react to input under ViewPause, ViewControlsHelp
1392 begin
1393 if CheckboxAdvancedPlayer.Checked then
1394 { uncomment to see less advanced versions }
1395 //UpdatePlayerByVelocityAndRay(SecondsPassed, HandleInput)
1396 //UpdatePlayerByVelocityAndRayWithDblJump(SecondsPassed, HandleInput)
1397 //UpdatePlayerByVelocityAndPhysicsRayWithDblJump(SecondsPassed, HandleInput)
1398 UpdatePlayerByVelocityAndPhysicsRayWithDblJumpShot(SecondsPassed, HandleInput)
1399 else
1400 UpdatePlayerSimpleDependOnlyVelocity(SecondsPassed, HandleInput);
1401 end;
1402 end;
1403
1404 function TViewPlay.Press(const Event: TInputPressRelease): Boolean;
1405 begin
1406 Result := inherited;
1407 if Result then Exit; // allow the ancestor to handle keys
1408
1409 { This virtual method is executed when user presses
1410 a key, a mouse button, or touches a touch-screen.
1411
1412 Note that each UI control has also events like OnPress and OnClick.
1413 These events can be used to handle the "press", if it should do something
1414 specific when used in that UI control.
1415 The TViewPlay.Press method should be used to handle keys
1416 not handled in children controls.
1417 }
1418
1419 if Event.IsKey(keyF5) then
1420 begin
1421 Container.SaveScreenToDefaultFile;
1422 Exit(true);
1423 end;
1424
1425 if Event.IsKey(keyEscape) and (Container.FrontView = ViewPlay) then
1426 begin
1427 ClickPause(nil);
1428 Exit(true);
1429 end;
1430 end;
1431
1432 procedure TViewPlay.ClickPause(Sender: TObject);
1433 begin
1434 PauseGame;
1435 ResumeGameScheduled := true;
1436 Container.PushView(ViewPause);
1437 end;
1438
1439 end.