Debian Codegraph @

examples/space_shooter/code/gameviewmain.pas

raw
1 {
2 Copyright 2019-2024 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 view, where most of the application logic takes place. }
17 unit GameViewMain;
18
19 interface
20
21 uses Classes,
22 CastleVectors, CastleComponentSerialize, CastleUIControls, CastleControls,
23 CastleKeysMouse, CastleViewport, CastleTransform, CastleTimeUtils,
24 GameTilingBackground, GameRocketsManager, GameRocksManager;
25
26 type
27 { Main view, where most of the application logic takes place. }
28 TViewMain = class(TCastleView)
29 published
30 { Components designed using CGE editor.
31 These fields will be automatically initialized at Start. }
32 LabelFps: TCastleLabel;
33 MainViewport: TCastleViewport;
34 SpaceShip: TCastleTransform;
35 RocketsParent: TCastleTransform;
36 RocksParent: TCastleTransform;
37 RectArmedHint: TCastleRectangleControl;
38 private
39 LifeTime: TFloatTime;
40 RocketsManager: TRocketsManager;
41 RocksManager: TRocksManager;
42 TilingBackground: TTilingBackground;
43 public
44 constructor Create(AOwner: TComponent); override;
45 procedure Start; override;
46 procedure Update(const SecondsPassed: Single; var HandleInput: Boolean); override;
47 procedure Resize; override;
48 end;
49
50 var
51 ViewMain: TViewMain;
52
53 implementation
54
55 uses SysUtils, Math,
56 CastleRectangles, CastleUtils;
57
58 { TViewMain ----------------------------------------------------------------- }
59
60 constructor TViewMain.Create(AOwner: TComponent);
61 begin
62 inherited;
63 DesignUrl := 'castle-data:/gameviewmain.castle-user-interface';
64 end;
65
66 procedure TViewMain.Start;
67 const
68 CannonsCount = 3;
69 var
70 I: Integer;
71 begin
72 inherited;
73
74 TilingBackground := TTilingBackground.Create(FreeAtStop);
75 TilingBackground.Translation := Vector3(0, 0, -100); // put in the back
76 TilingBackground.UpdateCoordinates(MainViewport);
77 MainViewport.Items.Add(TilingBackground);
78
79 RocketsManager := TRocketsManager.Create(FreeAtStop);
80 RocketsManager.RocketsParent := RocketsParent;
81 SetLength(RocketsManager.Cannons, CannonsCount);
82 for I := 0 to CannonsCount - 1 do
83 RocketsManager.Cannons[I] := DesignedComponent('Cannon' + IntToStr(I)) as TCastleTransform;
84 RocketsManager.InitializeCannons;
85 { RocketsManager is a UI element, it has to be inserted into the UI hierarchy.
86 It doesn't actually display anything, but it can listen to events like Update
87 and have children like TCastleTimer. }
88 InsertFront(RocketsManager);
89
90 RocksManager := TRocksManager.Create(FreeAtStop);
91 RocksManager.RocksParent := RocksParent;
92 RocksManager.InitializeRockResources(MainViewport);
93 InsertFront(RocksManager);
94 end;
95
96 procedure TViewMain.Update(const SecondsPassed: Single; var HandleInput: Boolean);
97
98 { Move the spaceship by DeltaSign,
99 where each DeltaSign component is either -1, 0 or 1.
100
101 The movement is clamped to the allowed range AllowedPositions.
102
103 The total movement distance cannot be more than MaxDelta.
104 Both MaxDelta components have to be >= 0.
105 Honoring MaxDelta is important to avoid "ping-pong" movement
106 around the desired position, when the mouse is very close to the spaceship. }
107 procedure MoveSpaceShip(const DeltaSign: TVector2Integer; const MaxDelta: TVector2);
108 const
109 MoveSpeed = 1000;
110 // Allowed SpaceShip.Translation.XY range
111 AllowedPositions: TFloatRectangle = (Left: -400; Bottom: -400; Width: 800; Height: 800);
112 var
113 NewTranslation, Delta: TVector2;
114 begin
115 Assert((DeltaSign.X = 0) or (DeltaSign.X = 1) or (DeltaSign.X = -1));
116 Assert((DeltaSign.Y = 0) or (DeltaSign.Y = 1) or (DeltaSign.Y = -1));
117 Assert(MaxDelta.X >= 0);
118 Assert(MaxDelta.Y >= 0);
119
120 // calculate Delta as is the vector we move if DeltaSign is (1,1)
121 Delta := Vector2(
122 MoveSpeed * SecondsPassed,
123 MoveSpeed * SecondsPassed
124 );
125 MinVar(Delta.X, MaxDelta.X);
126 MinVar(Delta.Y, MaxDelta.Y);
127
128 NewTranslation := SpaceShip.TranslationXY + Vector2(
129 // multiply TVector2 * TVector2Integer, component-wise
130 Delta.X * DeltaSign.X,
131 Delta.Y * DeltaSign.Y
132 );
133
134 ClampVar(NewTranslation.X, AllowedPositions.Left, AllowedPositions.Right);
135 ClampVar(NewTranslation.Y, AllowedPositions.Bottom, AllowedPositions.Top);
136
137 SpaceShip.TranslationXY := NewTranslation;
138 end;
139
140 { Get desired delta to move from mouse position.
141 Resulting vector contains the maximum move vector,
142 that would result spaceship to teleport towards the mouse. }
143 function GetMovementDirectionFromMouse: TVector2;
144 const
145 DistanceToReact = 5;
146 var
147 SpaceShipDesiredTranslation: TVector2;
148 begin
149 SpaceShipDesiredTranslation := MainViewport.PositionTo2DWorld(
150 Container.MousePosition, true);
151 Result := SpaceShipDesiredTranslation - SpaceShip.TranslationXY;
152
153 if Abs(Result.X) < DistanceToReact then
154 Result.X := 0;
155 if Abs(Result.Y) < DistanceToReact then
156 Result.Y := 0;
157 end;
158
159 { Allow player to move the spaceship by keys or mouse/touch. }
160 procedure UpdateMoveSpaceShip;
161 var
162 MovementDirectionFromMouse, MaxDelta: TVector2;
163 DeltaSign: TVector2Integer;
164 begin
165 DeltaSign := TVector2Integer.Zero;
166
167 if Container.MousePressed = [] then
168 begin
169 // move with keys, if no mouse button is pressed
170 if Container.Pressed[keyArrowLeft] or Container.Pressed[keyA] then
171 DeltaSign.X := DeltaSign.X - 1;
172 if Container.Pressed[keyArrowRight] or Container.Pressed[keyD] then
173 DeltaSign.X := DeltaSign.X + 1;
174 if Container.Pressed[keyArrowUp] or Container.Pressed[keyW] then
175 DeltaSign.Y := DeltaSign.Y + 1;
176 if Container.Pressed[keyArrowDown] or Container.Pressed[keyS] then
177 DeltaSign.Y := DeltaSign.Y - 1;
178 // large values, we don't want MaxDelta to limit movement in this case
179 MaxDelta := Vector2(1000, 1000);
180 end else
181 begin
182 // move with mouse, if any mouse button is pressed
183 MovementDirectionFromMouse := GetMovementDirectionFromMouse;
184 DeltaSign.X := Sign(MovementDirectionFromMouse.X);
185 DeltaSign.Y := Sign(MovementDirectionFromMouse.Y);
186 MaxDelta.X := Abs(MovementDirectionFromMouse.X);
187 MaxDelta.Y := Abs(MovementDirectionFromMouse.Y);
188 end;
189
190 if not DeltaSign.IsZero then
191 MoveSpaceShip(DeltaSign, MaxDelta);
192 end;
193
194 procedure UpdateBackground;
195 const
196 BackgroundMoveSpeed = 1.0;
197 begin
198 TilingBackground.ImageOrigin := Vector2Double(BackgroundMoveSpeed * LifeTime, 0.0);
199 TilingBackground.UpdateCoordinates(MainViewport);
200 end;
201
202 begin
203 inherited;
204 { This virtual method is executed every frame (many times per second). }
205
206 Assert(LabelFps <> nil, 'If you remove LabelFps from the design, remember to remove also the assignment "LabelFps.Caption := ..." from code');
207 LabelFps.Caption :=
208 'FPS: ' + Container.Fps.ToString + NL +
209 'Rockets existing count: ' + IntToStr(RocketsParent.Count) + NL +
210 'Rocks existing count: ' + IntToStr(RocksParent.Count) + NL +
211 'Rocks destroyed: ' + IntToStr(RocksManager.RocksDestroyed);
212
213 { Sum up SecondsPassed values into LifeTime (type TFloatTime = Double).
214 This keeps them precise, even after a long play, when the value gets large. }
215 LifeTime := LifeTime + SecondsPassed;
216
217 UpdateMoveSpaceShip;
218 UpdateBackground;
219
220 RocketsManager.ShootsArmed := Container.Pressed[keySpace];
221 if RocketsManager.ShootsArmed then
222 RectArmedHint.Border.AllSides := 1
223 else
224 RectArmedHint.Border.AllSides := 0;
225 end;
226
227 procedure TViewMain.Resize;
228 begin
229 inherited;
230 TilingBackground.UpdateCoordinates(MainViewport);
231 end;
232
233 end.