Debian Codegraph @

examples/physics/physics_persistent_forces_components/code/forcebehavior.pas

raw
1 {
2 Copyright 2022-2022 Michalis Kamburelis, Andrzej Kilijański.
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 { TForceBehavior }
17 unit ForceBehavior;
18
19 interface
20
21 uses
22 Classes, SysUtils, CastleTransform, CastleBehaviors, CastleVectors,
23 CastleComponentSerialize, CastleClassUtils, AbstractTimeDurationBehavior;
24
25 type
26 { Add this behavior to another body and select body you want to use it }
27 TForceBehavior = class(TAbstractTimeDurationBehavior)
28 private
29 FValue: Single;
30 FTarget: TCastleTransform;
31
32 public
33 procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override;
34
35 function PropertySections(const PropertyName: String): TPropertySections; override;
36 published
37 property Target: TCastleTransform read FTarget write FTarget;
38 property Value: Single read FValue write FValue;
39 end;
40
41 implementation
42
43 { TForceBehavior ------------------------------------------------------------- }
44
45 procedure TForceBehavior.Update(const SecondsPassed: Single;
46 var RemoveMe: TRemoveType);
47 var
48 RigidBody: TCastleRigidBody;
49 Direction: TVector3;
50 begin
51 inherited Update(SecondsPassed, RemoveMe);
52
53 if not ShouldUpdate then
54 Exit;
55
56 if FTarget = nil then
57 Exit;
58
59 if not FTarget.ExistsInRoot then
60 Exit;
61
62 RigidBody := FTarget.FindBehavior(TCastleRigidBody) as TCastleRigidBody;
63 if (RigidBody <> nil) and (RigidBody.ExistsInRoot) then
64 begin
65 { TODO: Parent.LocalToWorld(Parent.Translation) is wrong -
66 Parent.Translation is in Parent.Parent coord system. }
67 Direction := FTarget.LocalToWorld(FTarget.Translation) - Parent.LocalToWorld(Parent.Translation);
68 Direction := Direction.Normalize;
69 RigidBody.AddForceAtPosition(Direction * Value, Parent.LocalToWorld(Parent.Translation));
70 RigidBody.WakeUp;
71 end;
72 end;
73
74 function TForceBehavior.PropertySections(const PropertyName: String
75 ): TPropertySections;
76 begin
77 if (PropertyName = 'Target') or
78 (PropertyName = 'Value') then
79 Result := [psBasic]
80 else
81 Result := inherited PropertySections(PropertyName);
82 end;
83
84 initialization
85 RegisterSerializableComponent(TForceBehavior, 'Force Behavior');
86
87 end.
88